在函数last_letter() 行c = NULL将导致此程序在while(* c) 处发生段错误。什么原因?将字符指针设置为NULL并将其重新分配给它?我认为将指针设置为NULL并将其重新分配给其他内容是可以接受的?设置char *为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.
}
如果将'c'设置为NULL,则其他线程*可能尝试使用'* c',而'c'为NULL。 – immibis