首页 > 解决方案 > 打印指向 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 数组指针。然后我们 malloc 这些指针以适应用户输入的字符串,然后重新分配以适应更多字符串。

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

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

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

标签: carrayspointerschar

解决方案


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

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

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

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


推荐阅读