gpt4 book ai didi

c - 调整数组大小后出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:26 24 4
gpt4 key购买 nike

我正在尝试实现一种算法,该算法按字母顺序对长度不超过 100 个字符的单词进行排序。我的想法是使用 fgets() 获取每个单词,然后检查其长度是否小于 100 个字符,如果是,则在相应调整大小后将其放入一个字符串数组中。

但是,现在我在第 37 行遇到段错误,它应该使用 strcpy() 函数将字符串放入我的字符串数组中。

我很确定数组大小的调整是导致错误的原因。这是因为段错误只发生在第 2 个单词(即 while 循环的第 2 次迭代)。

这是我用过的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

int cmpstr(const void* a, const void* b){
const char* aa = *(const char**)a;
const char* bb = *(const char**)b;
return strcmp(aa,bb);
}

int main(int argc, char* argv[]){

//buffer array to check word length
char barray[102];
char* buffer = barray;

//main array pointer
char** list;
list = (char**)calloc(1, sizeof(char*));
//if calloc fails
if(list == NULL){
perror("calloc() fails at main array");
return -1;
}

//memory allocation for first string
list[0] = (char*) calloc(102, sizeof(char));
if(list[0] == NULL){
perror("calloc() fails at first array element");
return -1;
}

//string array index
int counter = 0;

//print flag
int flag = 0;

//create unsorted list
while(fgets(buffer, 103, stdin) != NULL){
//breakpoint 1
if(buffer[0] == '\n'){
break;
}
for(int i = 0; i < 101;i++){
//if word is of legit length and not the last one
if(buffer[i] == '\n'){
buffer[i] = '\0';
strcpy(list[counter], buffer); //segfault at 2nd iteration
counter++;
list = realloc(list, (counter + 1) * sizeof(char*));
list[counter] = (char*)calloc(102,sizeof(char));
flag = 1;
break;
}
}

if(flag==1){
flag = 0;
break;
}
//if word is too long
if(buffer[100] != '\0'){
printf("Word too long!");
}
else{
strcpy(list[counter], buffer);
counter++;
}

}

//sort list
qsort(list, counter, sizeof(char*), cmpstr);

//print list
for(int i = 0; i < counter; i++){
printf("%s\n", list[i]);
}

//free memory
for(int i = 0; i < counter; i++){
free(list[counter]);
}
}

PS:另外,如果您看到我犯的任何其他错误,请随时批评我的代码 :)

最佳答案

是的,看起来你设置了 list = (char**)calloc(1, sizeof(char*)); 这意味着你只有一个 char*list 中。因此,当您尝试将 strcpy 放入 list[1] 时,您会遇到段错误。

关于c - 调整数组大小后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746750/

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