ryyst
ryyst

Reputation: 9799

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?

Upvotes: 1

Views: 3364

Answers (4)

arodmon
arodmon

Reputation: 1

You create strfree() function and it is not used inside the code. The memory need to be free always, if it is not used.

if (!tmp) {
    printf("failure");
    if (!(*s) && !((*s)->buf))
       strfree(&(*s));
    exit(-1);
}

Looking strfree(), looks as you reserved memory for *s too in somewhere. Do the same before your code finish.

if (!(*s) && !((*s)->buf))
   strfree(&(*s));

Upvotes: 0

cendar
cendar

Reputation: 34

Like this mtrace said "No memory leaks"

char *strnappnd(str **s, const char *buf, size_t n) {
    ...
    return (*s)->buf;
}
void strfree(str *s){
    free(s->buf);
    free(s);
}

using the sample code given by Frerich

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

Upvotes: 0

aaz
aaz

Reputation: 5196

If you wrote

(*s)->buf = realloc((*s)->buf, nalloclen)

that would be a memory leak, because if realloc fails and returns NULL, you lose the (*s)->buf pointer, which is still pointing to allocated memory.

Since you exit on failure it's not a problem, but maybe your static analyser ignores the exit?

Upvotes: 0

Frerich Raabe
Frerich Raabe

Reputation: 94549

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.

Upvotes: 1

Related Questions