pthread_join函数执行异常

写了个程序,资县成立malloc内存,然后没释放(内存泄露),pthread_join获取返回结果,在不同的编译选项下,执行结果不同,这是为啥?

要通过汇编语言看?https://godbolt.org/

#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;
}

执行结果:

[root c++]#gcc -g -O0 -o pthread pthread.c -lpthread
[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++]#
[root c++]#./pthread
b is .
[root c++]#gcc -g -O2 -o pthread pthread.c -lpthread
[root c++]#./pthread
b is .
阅读 3.3k
1 个回答

没有return a; 不同的优化级别 rax不一定是保留着a

    strcpy(a,"hello world");
    return a;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题