使用pthread_join()后字符串损坏的C多线程代码问题排查
多线程程序字符串损坏问题的修复点
你的代码存在两个关键问题,直接导致了字符串输出乱码,具体修复位置如下:
1. 字符串内存分配严重不足
data_shared->ret = malloc(sizeof(char)); 仅分配了1字节内存,但你要存储的初始字符串"thread 1"(含终止符共9字节)、后续的"This is a test"(含终止符共15字节)都需要远大于1字节的空间。内存不足引发缓冲区溢出,会破坏内存中其他区域的数据,最终出现乱码。
修复方式:分配足够容纳目标字符串的内存,建议基于字符串长度+1(预留终止符\0的空间):
// 按最长目标字符串分配内存,兼容初始和后续的字符串存储 data_shared->ret = malloc(strlen("This is a test") + 1);
2. pthread_join参数类型错误
pthread_join(thid, data_shared) 中第二个参数要求是void**类型,用于接收线程返回的指针。你直接传入data*类型的data_shared,会导致内存被非法覆盖,破坏结构体里的指针数据,这也是乱码的核心诱因之一。
修复方式:传入void*类型的指针地址;如果不需要接收线程返回值,也可以直接传NULL:
void* thread_ret; if (pthread_join(thid, &thread_ret) != 0) { perror("pthread_join() error"); exit(3); } // 无需返回值时可简化为: // pthread_join(thid, NULL);
修复后的完整代码
#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct data { char *ret; int i; } data; void *thread(data* data_shared) { printf("thread() entered with argument '%s' and %d \n", data_shared->ret, data_shared->i); strcpy(data_shared->ret, "This is a test"); data_shared->i += 1; pthread_exit(data_shared); } int main() { pthread_t thid; data* data_shared; data_shared = malloc(sizeof(data)); data_shared->i = 1; // 分配足够存储最长目标字符串的内存 data_shared->ret = malloc(strlen("This is a test") + 1); strcpy(data_shared->ret, "thread 1"); if (pthread_create(&thid, NULL, (void*(*)(void*))thread, data_shared) != 0) { perror("pthread_create() error"); exit(1); } void* thread_ret; if (pthread_join(thid, &thread_ret) != 0) { perror("pthread_join() error"); exit(3); } printf("thread exited with '%s' and %d \n", data_shared->ret, data_shared->i); free(data_shared->ret); free(data_shared); return 0; }
修复后运行结果
thread() entered with argument 'thread 1' and 1 thread exited with 'This is a test' and 2
内容的提问来源于stack exchange,提问作者Cloud Cho
相关产品推荐
相关产品推荐

