【发布时间】:2019-04-06 12:57:50
【问题描述】:
我正在使用 malloc 为数组分配内存。我意识到,如果我在线程中使用 malloc 并且该线程停止执行,我将无法访问上述数组。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 2
#define N 4
void *threadWithoutMalloc(int *vector)
{
int i;
for (i = 0; i < N; i++)
{
vector[i] = i + 1;
}
return NULL;
}
void *threadWithMalloc(int *vector)
{
vector = malloc(sizeof(int) * N);
int i;
for (i = 0; i < N; i++)
{
vector[i] = i + 1;
}
return NULL;
}
int main()
{
//Generic stuff
pthread_t *threads;
threads = malloc(NUM_THREADS * sizeof(pthread_t));
int rc;
long t;
int **pointer_vector = malloc(N * sizeof(int *));
//Allocating the vector before entering the thread
pointer_vector[0] = malloc(sizeof(int)*N);
rc = pthread_create(&threads[0], NULL, (void *)threadWithoutMalloc, pointer_vector[0]);
if (rc)
{
printf("Error! Code %d\n", rc);
}
//Allocating the vector inside the thread
rc = pthread_create(&threads[1], NULL, (void *)threadWithMalloc, pointer_vector[1]);
if (rc)
{
printf("Error! Code %d\n", rc);
}
//Waiting for the threads to finish executing
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
//This works
printf("%d\n", pointer_vector[0][0]);
//This results in a segmentation fault
printf("%d\n", pointer_vector[1][0]);
return 0;
}
为什么会这样?我目前的假设是,在线程运行其进程后,它的内存被释放。但是,我使用的是动态分配,并将结果存储在main() 上声明的变量中。我只是想更好地了解发生了什么。
【问题讨论】: