Search code examples
cmemory-managementrealloc

realloc - memory leak


I got some C code:

typedef struct {
    size_t len;
    size_t alloclen;
    char *buf;
} str;

void strnappnd(str **s, const char *buf, size_t n) {

    if ((*s)->len + n >= (*s)->alloclen) {
        size_t nalloclen = (*s)->len + n + 1;
        void *tmp = realloc((*s)->buf, nalloclen);
        if (!tmp) {
            printf("failure");
            exit(-1);
        }
        (*s)->buf = tmp;
        (*s)->alloclen = nalloclen;
    }
    memccpy((*s)->buf + (*s)->len, buf, '\0', n);
    (*s)->len += n;
    (*s)->buf[(*s)->len] = '\0';
}

void strfree(str **s) {
    free((*s)->buf);
    free(*s);
    *s = NULL;
}

Apparently, the strnappnd leaks at the realloc line. Why?


Solution

  • Consider:

    void f() {
      str *s = (str *)malloc(sizeof(str));
      s->len = 5;
      s->alloclen = 5;
      s->buf = strdup("Hello");
      strnappend(&s, " World!", 7);
      free(s); /* courtesy of Eric */
    }
    

    If you had something like that, the memory allocated by realloc() would leak as f() is left.