Possible Stack Corruption

会有一股神秘感。 提交于 2019-12-06 03:43:26

Write a new source file with a main function that does the same things as the main you posted here except rather than using pthread_create just call the function. See if you can recreate the issue independent of using threads. From the way things look your semaphores should still work just fine in a single threaded environment.

If this still fails you will have an easier time debugging it.

Since you said that calling exit rather than returning did not yield the error it would suggest that you have corrupted either the return address that is on the stack when runner is started. By calling exit you don't rely on this memory area to get to an exiting function (if you had returned pthread_exit would have been called by the pthread library code that had called runner). I think that the valgrind output is not 100% accurate -- not due to any fault in valgrind, but because the place where you are triggering the error coupled with the type of error you are triggering makes this very difficult to be sure who called what.

Some gcc flags you may be interested in:

-fstack-protector-all -Wstack-protector

The warning option doesn't work without the -f option here.

You may also want to try:

-fno-omit-frame-pointer

All the important parts are missing in your code, but the most common reasons for stack corruption:

  • Storing a pointer to an element on the stack and using it after the object is already out of scope.
  • Buffer overrun, like having a char buffer[20] on the stack and writing outside the bounds (sprintf is a fantastic way to accomplish that).
  • Bad cast, i.e. having a base class A on the stack, casting it to a derived class and using it.

Use valgrind or an equivalent memory checking tool to figure it out. Stop guessing. Also stop posting incomplete code, especially if you don't know if it has a problem or not. The bug could be outside of this function. For exemple, maybe the semaphore isn't initialized.

From the valgrind output, i can suggest that your pthread_create() line must contains a invalid function pointer. So pthread jumps to that fake address, and crashes. Obviously there is no stack ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!