#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define EXIT_ON_NOT_ZERO(assignment, msg) if((assignment)!=0) { perror(msg); exit(EXIT_FAILURE); }
void* produce(void* args) {
return (void*) 1;
}
void* consume(void* args) {
return (void*) 1;
}
int main() {
pthread_t producer;
pthread_t consumer;
void* producerStatus;
void* consumerStatus;
EXIT_ON_NOT_ZERO(pthread_create(&producer, NULL, &produce, NULL), "Creating producer thread");
EXIT_ON_NOT_ZERO(pthread_create(&consumer, NULL, &consume, NULL), "Creating consumer thread");
EXIT_ON_NOT_ZERO(pthread_join(producer, &producerStatus), "Joining producer thread");
EXIT_ON_NOT_ZERO(pthread_join(consumer, &consumerStatus), "Joining consumer thread");
printf("Producer exited with status: %d\n", *(int*)producerStatus);
printf("Consumer exited with status: %d\n", *(int*)consumerStatus);
exit(EXIT_SUCCESS);
}
我不明白为什么我不能同时进行强制转换和取消引用。
代码在到达第一个 printf
时会导致 SEGFAULT
。
最佳答案
您不能这样做,因为 (void *) 1
返回地址 0x01
并且取消引用它很可能是未定义的行为。
也许,您想将“地址”转换为intptr_t
,这根据标准是完全有效的。
关于c - 转换和取消引用 void* 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916898/