尝试使用 realloc(),获取核心转储

Trying to use realloc(), getting core dumped

我正在尝试编写一个小程序,它使用 realloc()、getchar() 和一些指针算法在内存中存储字符数组。

我有一个名为 "inputArray" 的函数(在 convert.c 中),它接收一个指向 char 的指针(开始时为 NULL,在 main.c 中声明),然后重新分配使用一个字符,直到 getchar() 得到一个 '\n' 字符。这些函数似乎工作正常,但是当我尝试在 main.c 中打印回字符串时,我收到 "segmentation fault (core dumped)" 错误。我一直在寻找几个小时,找不到问题出在哪里。谢谢!

main.c:

# include "convert.h"

int main()
{
  char * string = NULL;
  inputArray(string);
  printf("%s", string);    
  free(string);
  return 0;
}

convert.c:

#include "convert.h"

void inputArray(char * array)
{
    /*pointer to the array*/
    char * ptr = NULL;

    /*stores the char*/
    char c = 0;

    /*counter used for pointer arithmetic*/
    int count = 0;

    /*loop for getting chars in array*/
    while ((c = getchar()) != '\n')
    {
      array = realloc(array, sizeof(char));
      ptr = array + count;
      *ptr = c;
      ++count;
    }

    /*add the null char to the end of the string*/
    array = realloc(array, sizeof(char));
    ptr += count;
    *ptr = '[=11=]';
}

convert.h:

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

void inputArray(char * array);

您在 inputArray 函数中缺少一级间接寻址。它应该声明为

void inputArray(char **array)

它应该像这样重新分配(您还需要通过乘以 count + 1 来增加数组的大小)

*array = realloc(*array, (count + 1) * sizeof(char));

这样称呼它:

 inputArray(&string);

新分配的数组大小不正确。您必须分配 count + 1 个字符。

array = realloc(array, ( count + 1 ) * sizeof(char));

考虑到使用临时指针重新分配内存更安全。否则之前分配的内存原地址会丢失

还有这些说法

array = realloc(array, sizeof(char));
ptr += count;

错了。你至少应该写

array = realloc(array, count * sizeof(char));
ptr = array + count - 1;

函数也应该这样声明

char * inputArray(char * array);

并且它必须 return 指向调用者的新指针。

主要是你必须写

string = inputArray(string);

否则函数应通过引用接受参数,即参数应声明为

void inputArray(char ** array);

并在函数中进行相应处理