//main.c#include "test.h"
void main(){
S* s = get_struct_s();
printf("%s\n",s->name);
return 0;
}
//test.h
typedef struct S_{
...
char name[8];
} S;
S* s_array[10];
//test.c
#include "test.h"
S* get_struct_s(){
return s_array[0];
}
在大型程序中,复杂的Makefile可能会通过上面这种project(即能够编译成功),但是在执行过程中printf语句会crush,经过gdb定位,是get_struct_s返回了一个错误的指针。但是,这个指针在get_struct_s内部的时候是正确的。例如正确的指针是0xaa12345678,返回之后变成了0xffffffff12345678,经过比较可以明显看出后四个字节是相同的,函数返回时正确的指针被截断为4个字节了。
原因是test.h中没有声明get_struct_s函数,编译器为get_struct_s函数的返回值预留了4个字节,但是实际返回的指针大于4个字节,产生了截断,这种bug很不容易察觉。
解决方法是在test.h中声明函数。
解决方法是在test.h中声明函数。