【问题标题】:Trying to use realloc(), getting core dumped尝试使用 realloc(),导致核心转储
【发布时间】:2016-12-07 15:44:33
【问题描述】:

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

我有一个名为“inputArray”的函数(在 convert.c 中),它接收一个指向 char 的指针(以 NULL 开头,在 main.c 中声明),然后用一个 char 重新分配,直到 getchar() 得到一个 '\n' 字符。这些功能似乎工作正常,但是当我尝试在 main.c 中打印回字符串时,我收到“分段错误(核心转储)”错误。我一直在寻找几个小时,找不到问题所在。谢谢!

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 = '\0';
}

转换.h:

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

void inputArray(char * array);

【问题讨论】:

  • 搜索并阅读有关在 c 中模拟通过引用传递
  • sizeof(char) 总是 1.....(好吧,如果你使用双角字符,可能是 2 - 但它是固定大小,这不是你想要的)。

标签: c arrays dynamic-allocation


【解决方案1】:

新分配的数组大小不正确。你必须分配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);

它必须将新指针返回给调用者。

主要是你必须写

string = inputArray(string);

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

void inputArray(char ** array);

并在函数中进行相应处理。

【讨论】:

    【解决方案2】:

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

    void inputArray(char **array)
    

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

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

    这样称呼它:

     inputArray(&string);
    

    【讨论】:

    • @BeyelerStudios 哎呀,匆忙的结果:-)
    • @BeyelerStudios 谢谢 :-)
    猜你喜欢
    • 2015-11-18
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2021-07-19
    相关资源
    最近更新 更多