struct data *getData() { struct data *ret = (struct data *)malloc(sizeof(struct data)); printf("ret is %p\r\n", ret); return ret; }
// truncret.c #include "common.h"
void showData(struct data *pdata) { printf("data is a = %d, b = %d \r\n", pdata->a, pdata->b); }
int main() { struct data *ret = getData(); printf("get ret is %p\r\n", ret); ret->a = 100; ret->b = 200; showData(ret);
free(ret);
return 0; }
直接把两个文件一起编译生成目标文件,可以看到有警告:
1 2 3 4 5 6 7 8 9 10
gcc truncret.c getData.c -o a truncret.c:11:24: warning: implicit declaration of function 'getData' is invalid in C99 [-Wimplicit-function-declaration] struct data *ret = getData(); ^ truncret.c:11:18: warning: incompatible integer to pointer conversion initializing 'struct data *' with an expression of type 'int' [-Wint-conversion] struct data *ret = getData(); ^ 2 warnings generated.
成功生成了目标文件,但是执行时段错误了。
1 2 3 4
Keep:sysrepo keep$ ./a ret is 0x7faf01402a70 get ret is 0x1402a70 Segmentation fault: 11
Keep:sysrepo keep$ gcc truncret.c getData.c -o a -Werror truncret.c:11:24: error: implicit declaration of function 'getData' is invalid in C99 [-Werror,-Wimplicit-function-declaration] struct data *ret = getData(); ^ truncret.c:11:18: error: incompatible integer to pointer conversion initializing 'struct data *' with an expression of type 'int' [-Werror,-Wint-conversion] struct data *ret = getData(); ^ ~~~~~~~~~ 2 errors generated.