Adam Adam - 2 months ago 9
C Question

Understanding free() buffer before return statement

I want to understand the behavior of returning a pointer from a function call. Suppose I have the following simple code:

int main(){
int i;
float *ssd;
ssd = test();

for (i = 0; i < 3; ++i) {
printf("%f, ", ssd[i]);
}
printf("\n \n");

memset(ssd, 0.0, 3*sizeof(float));

for (i = 0; i < 3; ++i) {
printf("%f, ", ssd[i]);
}
printf("\n \n");

}

float *test(){

float *buff = malloc(3* sizeof(float));
int i;
for (i = 0; i < 3; ++i) {
buff[i] = (float) (6.31 + i);
}

free(buff);
return buff;

}


As you see, I created a temporary buffer
buff
inside
test()
. Before I return, I freed
buff
before
return
statement. Although I tested it and the results were as expected, I don't understand how
test()
function could return
buff
values even though
free(buff)
is before
return
buff?

Answer

After

free(buff);

any further operations which dereference buff are undefined behaviour.

Your function test() allocates a buffer, but then frees it before returning it to main, as ssd.

So when ssd is dereferenced in main, although the pointer still has the same value it was allocated by malloc, it is no longer pointing to memory that you "own". So from then on, anything can happen. Your code may still work, or it may not.

Comments