c - 转换和取消引用 void* 时出现段错误

标签 c multithreading casting

    #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/

相关文章:

c - 在c中使用ptrace从另一个进程读取一 block 内存

c# - 从不同线程注册事件

java - 使用注释来监视/记录/报告线程访问给定方法的 Java 工具?

c# - 将对象转换为基础接口(interface)

c++ - 将 WIN32_FIND_DATA 转换为 LPVOID

php - 在 PHP 中将整数转换为字符串

c++ - C中UDP服务器和客户端的问题

c++ - 在 C 中使用 char 作为数组索引?

c - 释放二维动态数组时堆损坏

c# - 多线程是应用程序性能改进的答案吗