edit It appears that this is just a case of the sample code being wrong. Thanks for clearing this up, SO.
Looking at the following code/quote from http://staff.um.edu.mt/csta1/courses/lectures/csa2060/c8a.html
//f.c
#include <stdio.h>
#include <stdlib.h>
char *foo(char *);
main() {
char *a = NULL;
char *b = NULL;
a = foo("Hi there, Chris");
free(a);
b = foo("Goodbye");
free(b);
printf("From main: %s %s\n", a, b);
}
char *foo(char *p) {
char *q = (char *)malloc(strlen(p)+1);
strcpy(q, p);
printf("From foo: the string is %s\n", q);
return q;
}
If free(b) is omitted, then “Goodbye” can be seen to be written to the location of “Hi there, Chris”.
I don’t understand why you have to call free before using the variables being free’d in the printf() statement (indeed, in my mind it seems like freeing up the memory first would make this fail).
Apologies if this is a repeat, but having searched/read what I could find I’m still in the dark.
Code and quote are from here: http://staff.um.edu.mt/csta1/courses/lectures/csa2060/c8a.html
edit It appears that this is just a case of the sample code being wrong. Thanks for clearing this up, SO.
You call
free()when you won’t need to use the memory again.Your
printf()comes after you’ve freed both the strings, so you invoke ‘undefined behaviour’ (UB) when you try to print the strings. There is a moderate chance that you get the same address for bothaandbinmain(), in which case, you can only have one of the two strings stored in the space, of course. But that’s still UB and anything could happen.You should only call
free()after theprintf()inmain().