我的守则如下:
bool func(const MY_STRUCT *const ptr, some_struct *x, int y)
{
printf("IN: %p
", ptr); // ok
for (int i = 0; i < y; ++i) {
if (ptr->foo(x[i].key) == 0) {
return false;
}
}
printf("OUT: %p
", ptr); // ok
return true;
}
void process(void)
{
... ...
for (i = 0; i < num; ++i) {
MY_STRUCT *ptr = obj->GetPtr(); // success
printf("BEFORE: %p
", ptr); // ok
if (func(ptr, x, y) == false) {
continue;
}
printf("AFTER: %p
", ptr); // <nil> when compile with -O2
printf("%s", ptr->data); // *** segment fault here ***
}
}
产出:
BEFORE: 0x0612d3fa
IN: 0x0612d3fa
OUT: 0x0612d3fa
AFTER: <nil>
segment fault
If I compile above code with -O0, everything works fine.
However, if I compile it with -O2, after the function func
is called, the ptr
become NULL
!
这是否是一种诱骗? 是否有任何人遇到过类似的ug?
缩略语