【发布时间】:2017-02-13 23:55:42
【问题描述】:
在函数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.
}
【问题讨论】:
-
如果您将
c设置为NULL,那么其他线程 可能会在c为NULL 时尝试使用*c。
标签: c pointers segmentation-fault