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?