#include <pthread.h> #include <stdio.h> #include <stdlib.h> typedef struct { int num1; int num2; int *result; } ThreadArgs; void *thread_func(void *arg) { ThreadArgs *args = (ThreadArgs *)arg; int num1 = args->num1; int num2 = args->num2; int *result = (int *)malloc(sizeof(int)); *result = num1 + num2; args->result = result; return NULL; } int main() { pthread_t tid; ThreadArgs args = {123, 456, NULL}; int ret = pthread_create(&tid, NULL, thread_func, &args); if (ret != 0) { printf("pthread_create error: %d\n", ret); return -1; } printf("Main thread.\n"); pthread_join(tid, NULL); int *result = args.result; printf("The result is %d.\n", *result); free(result); return 0; } 上面代码有没有泄漏内存的风险 请优化
时间: 2024-03-26 11:35:25 浏览: 60
<pthread.h>库文件下载
以下是优化后的代码,解决了内存泄漏的问题:
```
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int num1;
int num2;
int *result;
} ThreadArgs;
void *thread_func(void *arg) {
ThreadArgs *args = (ThreadArgs *)arg;
int num1 = args->num1;
int num2 = args->num2;
int *result = (int *)malloc(sizeof(int));
*result = num1 + num2;
args->result = result;
pthread_exit(NULL); // 子线程结束时调用 pthread_exit() 释放内存
}
int main() {
pthread_t tid;
ThreadArgs args = {123, 456, NULL};
int ret = pthread_create(&tid, NULL, thread_func, &args);
if (ret != 0) {
printf("pthread_create error: %d\n", ret);
return -1;
}
printf("Main thread.\n");
pthread_join(tid, NULL);
int *result = args.result;
printf("The result is %d.\n", *result);
free(result); // 在主线程中释放内存
return 0;
}
```
优化的思路是,在子线程中使用`pthread_exit()`函数代替`return NULL`来结束线程,这样可以确保子线程结束时会被回收,从而避免内存泄漏。同时,在主线程中添加了释放内存的代码,确保释放子线程中动态分配的内存。
阅读全文