c - 将 char* 设置为 NULL 段错误

标签 c pointers segmentation-fault

在函数 last_letter() c = NULL 行将导致此程序在 while (*c) 处出现段错误 注释掉它不会。什么原因?将 char 指针设置为 NULL 并为其重新分配一些内容?我认为将指针设置为 NULL 并将它们重新分配给其他东西是可以接受的吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

char s1[] = "abcdefg";
char s2[] = "xyz";
char* c;

void last_letter(char* a, int i) {
  printf("last_letter ( a is %s and i is %d)\n", a, i);
  sleep(i);
  c = NULL;   // comment out, what is different?
  sleep(i);
  c = a;
  sleep(i);
  while (*c) {
    c++;
  }
  printf("%c\n", *(c-1));
  return;
}


// This function will run concurrently.

void* aa(void *ptr) {
  last_letter(s2, 2);
  return NULL;
}

int main() {
  pthread_t t1;
  int iret1 = pthread_create(&t1, NULL, aa, NULL);
  if (iret1) {
    fprintf(stderr,"Cannot create thread, rc=%d\n", iret1);
  }
  last_letter(s1, 5);
  sleep(10);
  printf("Ended nicely this time\n");
  return 0; //never reached when c = NULL is not commented out.
}

最佳答案

首先,这是一个典型的竞争条件。该程序取决于调用 aa() 的顺序。

pthread_create() 的最后一个参数是参数。从联机帮助页:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

因此,当通过 pthread 机制调用 aa() 时,a 参数为 NULL,因为 pthread_create() 是使用 NULL arg 调用的。

然后这个循环解引用一个 NULL 指针,导致崩溃:

c = a;
sleep(i);
while (*c) {
    c++;
}

所以给 pthread_create() 一个非 NULL 参数,你就走上了更好的轨道。

关于c - 将 char* 设置为 NULL 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215614/

相关文章:

c++ - 从 vector C++ 中删除对象时出现段错误

c - 如何在c中使用tcp套接字编程查找客户端ip地址

c - 高效地乘以 7

c# - 串口通信需要校验和

c - 段错误(核心已转储)

C段错误

c# - 为什么我不能在fixed语句中使用extern函数?

c++ - 动态内存分配被覆盖?

c - 合并排序不断循环并进入段错误

Python 解释器段错误