打印指向char指针数组的指针时的Segfault

问题描述 投票:-1回答:1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sortString(char *s[], int count);

int main(){

        int i;
        char buff[BUFSIZ];

        int count;
       // 's' is a pointer to a char pointer, initially 's' is allocated storage for one char pointer
        char** s= malloc(sizeof(char*));

        printf("Here is the list of unsorted names: \n\n");

        // Keep on reading unlimited number of names until EOF (Ctrl + D) is reached
        for (count = 0; fgets(buff, sizeof(buff), stdin); count++){

           //Step 1: allocate sufficient storage for s[n] to store the content in buff plus one byte for '\0'
           s[count]=malloc(strlen(buff)+1);
           //Step 2: copy the contents of 'buf' to 's[n]'
           strcpy(s[count],buff);
//Step 3: resize the array of pointers pointed to by 's' to increase its size for the next pointer
          *s=realloc(*s,sizeof(char **)*count+2);
          printf("added to the array at s[%i] is : %s",count, s[count]);
        }

       // EOF reached. Now count the number of strings read

        printf("\nCount is %d\n\n", count);

       // Now sort string using sortString function

       // Step 4: implement sortString function for the above-mentioned function declaration
       //sortString(s, count);

       // Step 5: print the list of sorted names.
       int k;
       for(k=0; k<count; k++){
         printf("%s", s[k]);
       }
       // Step 6:free the allocated memory.

        return 0;
}

void sortString(char *s[], int count){
  char * temp;
  int j,k;

  for(j = 0; j < count -1; j++){
    for(k=j+1; k < count; k++){
      if(strncmp(s[k],s[k+1],1)>0){
        temp=s[k];
        s[k]=s[k+1];
        s[k+1] = temp;

      }

    }
  }

}

完全披露,这是一个功课。

这个想法是这样的:我们有一个指针,指向更多的char指针,它们是char数组指针本身。然后我们对这些指针进行malloc以适应用户输入的字符串,然后重新分配以适应更多的字符串。

malloc和realloc看起来很好。我添加了一行来检查我在每个数组索引中添加的内容,它似乎工作得很好。

当我尝试打印它时会出现问题。我在第5步遇到了段错误,特别是printf语句。看起来s [k]将适用于4之前的任何正整数,因为当k大于4时它会发生段错误。

使用gcc -g,ubuntu 18.04和windows 10编译。所有人都面临同样的问题。

c arrays pointers char
1个回答
0
投票

除了@ chux的操作修复顺序之外,你的realloc语句也存在一个主要问题。你这样做:

*s = realloc(*s, ...)

这意味着你没有将新分配的内存分配给s,你正在重新分配和分配去参考的s,基本上是s[0]。这意味着您正在重新分配为字符串分配的内存,而不是字符串数组。

我不完全确定为什么它不会更早地遇到段错误,或者为什么它会通过一些打印,但这是内存访问违规的本质。您可能会在每次运行的不同时间崩溃,这是不可预测的。

© www.soinside.com 2019 - 2024. All rights reserved.