Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asprintf(): how to free the pointers?

Tags:

c

linux

I have code like this: I assigned log twice, is there potential memory leak for the first &log?

char *log = NULL;
asprintf(&log, "Hello: %s", name);
if (known_person== true){
    asprintf(&log, "%s, %s", log, ", my old friend.");
}
free (log);
like image 678
Howard Shane Avatar asked Sep 04 '15 20:09

Howard Shane


1 Answers

Yes, the code will leak, since asprintf neither checks, nor attempts to reuse, the previous pointer. Hence, the memory is simply lost. The best way to avoid the problem in your example would be to rewrite the code as

char *log = NULL;
if (known_person== true)
    asprintf(&log, "Hello: %s, my old friend.", name);
else
    asprintf(&log, "Hello: %s", name);

free (log);

That way, the buffer is allocated once and freed correctly.

Alternatively, you could use two pointers

char *temp = NULL;
asprintf(&temp, "Hello: %s", name);

char *log = NULL;
if (known_person== true) {
    asprintf(&log, "%s, my old friend.", temp);
    free( temp );
}
else {
    log = temp;
}

free (log);
like image 185
user3386109 Avatar answered Sep 22 '22 14:09

user3386109