#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[] ) { char* output = "\0";
The string literals "\ 0" end automatically, you do not need to add them.
int counter = 5; while(counter > 0) { char buffer[20]; sprintf(buffer, "%u", counter); char* temp; temp = malloc((strlen(output) + strlen(buffer) + 1)); strcpy(temp, buffer); strcat(temp, output); char* oldmemory = output; output = temp; free(oldmemory);
This free() is called for the first time, freeing the initial value of the output, which is a pointer to the string literal "\0" . Calling free() for anything other than a valid pointer returned from *alloc() or NULL is undefined.
counter--; } printf("output: %s\n", output); free(output); return 0; }
valgrind reports:
==7125== Invalid free() / delete / delete[] ==7125== at 0x4024B3A: free (vg_replace_malloc.c:366) ==7125== by 0x8048662: main (foo.c:20) ==7125== Address 0x8048780 is not stack'd, malloc'd or (recently) free'd
This is not a memory leak; this is not true free() .
Philip potter
source share