这是我的代码:
int main() {
typedef struct {
int recordCount;
char *firstName;
char *secondName;
char *id;
char *email;
}student;
student *students = malloc(sizeof(*students));
int i = 0;
while (students[i].firstName[0] != '.'){
students[i].firstName = (char *)malloc(sizeof(char*));
scanf("%s", students[i].firstName);
i++;
students = realloc(students, sizeof(students) * (i + 1));
}
}
当我通过 for 循环运行它时它起作用了,我很确定这只是我的 while 循环发生的一些愚蠢的事情。
最佳答案
malloc
返回一 block 未初始化的内存。所以 students[i].firstName
是您尝试取消引用的未初始化指针。读取和取消引用未初始化的指针会调用未定义的行为,在本例中表现为崩溃。
当您确实为firstName
成员分配空间时,您只为其分配sizeof(char*)
字节,大小为一个指针,不一定是您要读取的字符串的长度。
创建一个缓冲区以将字符串读入其大小足以满足您可能需要的内容,然后使用 strdup
创建一个副本以分配给相关指针。
student *students = NULL;
int i = 0;
char str[100];
scanf("%99s", str);
while (str[0] != '.'){
students = realloc(students, sizeof(*students) * (i+1));
students[i].firstName = strdup(str);
i++;
scanf("%99s", str);
}
关于有人可以解释为什么我遇到段错误 11 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681860/