If I have the following code, where I allocate my memory in the main function and then pass it to a function, which fills it for me like this:
main()
{
char *bar = (char*) malloc(sizeof(char));
while(1)
{
foo(bar);
free(bar);
bar = (char*) malloc(sizeof(char));
}
}
foo(char *bar)
{
int c;
int i = 0;
while((c = getchar()) != '\n' && c != EOF)
{
bar[i++] = c;
bar = (char*) realloc(bar, sizeof(char) * (i+1));
}
}
I get a segfault after a few inputs. If I do this however:
main()
{
char *bar;
while(1)
{
bar = foo();
free(bar);
}
}
char *foo()
{
char *bar = (char*) malloc(sizeof(char));
int c;
int i = 0;
while((c = getchar()) != '\n' && c != EOF)
{
bar[i++] = c;
bar = (char*) realloc(bar, sizeof(char) * (i+1));
}
return bar;
}
, i.e. put the memory allocation to the function, everything seems to work fine. Why is that?
This is quite expected behaviour. realloc() may or may not “move” the pointer you pass into it to a new address. If that happens, it also free()’s the original address. Since C is pass-by-value and not pass-by-reference, the
barpointer in your main() function will still refer to the old address, and you’ll effectively do a double free (and the realloc()’d pointer will be lost).