【发布时间】:2020-06-04 16:51:55
【问题描述】:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
void* thread_function(void *ignoredInThisExample)
{
char *a = malloc(20);
strcpy(a,"hello world");
}
int main()
{
pthread_t thread_id;
char *b;
pthread_create (&thread_id, NULL,&thread_function, NULL);
pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
//value so to use that we need double pointer
printf("b is %s.\n",b);
return 0;
}
使用-O0和-O1编译运行:
[root c++]#gcc -g -O0 -o pthread pthread.c -lpthread
[root c++]#
[root c++]#
[root c++]#./pthread
b is hello world.
[root c++]#
[root c++]#
[root c++]#gcc -g -O1 -o pthread pthread.c -lpthread
[root c++]#
[root c++]#./pthread
b is .
为什么会这样?源代码来自pthread_join() and pthread_exit() 由于我不熟悉汇编语言,任何人都可以帮我分析原因吗? online assembly
【问题讨论】:
-
您的
thread_function中没有返回语句,导致未定义的行为。如果您return a;还会发生这种情况吗 -
顺便说一句,你为什么以 root 运行 gcc 和你编译的二进制文件?
-
@ChristianGibbons 谢谢,但是我在 man pthread_exit() 中什么也没找到,顺便说一下,这只是一个在局域网上运行的虚拟机,所以不要介意。