打印指向char指针数组的指针时出现段错误

时间:2019-02-26 04:37:59

标签: c arrays pointers char

#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;

      }

    }
  }

}

完全公开,这是一项作业。

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

malloc和realloc看起来不错。我添加了一行以检查我在每个数组索引处添加的内容,它似乎工作正常。

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

使用gcc -g,ubuntu 18.04和Windows 10进行编译。所有这些都面临相同的问题。

1 个答案:

答案 0 :(得分:0)

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

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

这意味着您没有将新分配的内存分配给s,而是重新分配并分配了被取消引用的s,本质上是s[0]。这意味着您要重新分配为字符串而不是字符串数组分配的内存。

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

相关问题