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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With