从函数返回指向复合文字的指针安全吗?
我知道函数的局部变量在函数返回后被释放,而malloc
d内存是一个例外.然而,当我试图返回指向复合文字的指针时,编译器没有给出任何警告.这是否意味着这样做是安全的?
我用gcc -Wall -o test test.c
以下代码编译时没有任何警告,并输出20
#include <stdio.h>
struct test {
int item;
struct test *next;
} struct_1 = { .item = 10, .next=NULL };
struct test * returnStruct(){
struct test * structPointer = (& ((struct test) { .item = 20, .next = NULL }));
return(structPointer);
}
int main(){
struct_1.next = returnStruct();
printf("%d", (struct_1.next)->item);
return(0);
}
但此代码会导致警告
#include <stdio.h>
int * testr(){
int i = 568;
return(&i);
}
int main(){
printf("%d", *testr());
return(0);
}
warning: address of stack memory associated with local variable 'i' returned [-Wreturn-stack-address]
return(&i);
^
1 warning generated.
另外,如果复合文字在函数返回后没有被释放,这是否意味着我需要对函数中的所有复合文字调用free
?