gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:05 25 4
gpt4 key购买 nike

在函数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com