gpt4 book ai didi

c - 可能的堆栈损坏

转载 作者:太空狗 更新时间:2023-10-29 15:53:34 25 4
gpt4 key购买 nike

引用我之前关于 GDB not pinpointing the SIGSEGV point 的问题,

我的线程代码如下:

void *runner(void *unused)
{
do
{
sem_wait(&x);
...

if(/*condition 1 check*/)
{
sem_post(&x);
sleep(5);
sem_wait(&x);
if(/*repeat condition 1 check; after atleast 5 seconds*/)
{
printf("LEAVING...\n");
sem_post(&x);
// putting exit(0); here resolves the dilemma
return(NULL);
}
}
sem_post(&x);
}while(1);

}

主要代码:

sem_t x;    

int main(void)
{
sem_init(&x,0,1);
...
pthread_t thrId;
pthread_create(&thrId,NULL,runner,NULL);
...
pthread_join(thrId,NULL);
return(0);
}

编辑:在运行线程代码中有一个 exit(0),使故障消失。


堆栈损坏背后的原因可能是什么?

GDB 输出:(0xb7fe2b70 是运行线程 ID)

LEAVING...
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb7fe2b70 (LWP 2604)]
0x00000011 in ?? ()

Valgrind 输出:

==3076== Thread 2:
==3076== Jump to the invalid address stated on the next line
==3076== at 0x11: ???
==3076== by 0xA26CCD: clone (clone.S:133)
==3076== Address 0x11 is not stack'd, malloc'd or (recently) free'd
==3076==
==3076==
==3076== Process terminating with default action of signal 11 (SIGSEGV)
==3076== Bad permissions for mapped region at address 0x11
==3076== at 0x11: ???
==3076== by 0xA26CCD: clone (clone.S:133)
==3076== Address 0x11 is not stack'd, malloc'd or (recently) free'd

最佳答案

使用 main 函数编写一个新的源文件,它的功能与您在此处发布的 main 相同,只是不使用 pthread_create调用函数。看看您是否可以独立于使用线程重新创建问题。从外观上看,您的信号量在单线程环境中应该仍能正常工作。

如果仍然失败,您将更容易调试它。

既然你说调用 exit 而不是返回不会产生错误,那么这表明你已经破坏了 runner 时堆栈上的返回地址开始了。通过调用 exit 你不依赖这个内存区域来获得退出函数(如果你已经返回 pthread_exit 将被调用 runner 的 pthread 库代码调用>).我认为 valgrind 输出不是 100% 准确——不是因为 valgrind 有任何错误,而是因为你触发错误的地方加上你触发的错误类型使得很难确定谁调用了什么.

一些您可能感兴趣的 gcc 标志:

-fstack-protector-all -Wstack-protector

此处如果没有 -f 选项,警告选项将不起作用。

您可能还想尝试:

-fno-omit-frame-pointer

关于c - 可能的堆栈损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com