【问题标题】:Reallocing a c array inside extern function在外部函数中重新分配 c 数组
【发布时间】:2018-05-26 16:59:50
【问题描述】:

您好,每次解析循环找到文件时,我都会尝试在我的 main() 中分配 char* 数组,然后在外部函数中分配 realloc。除了char * files[]mallocrealloc 之外,我的所有代码都有效。

当我运行以下代码时,我收到此错误

*** Error in `./Assignment2': double free or corruption (out): 0x00007ffcefe78e50 ***
======= Backtrace: =========
--Lots of memory locations listed--
Aborted (core dumped)

Main.c

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

int main(int argc, char *argv[]){
  char **files = malloc(sizeof(char*));

  /* parse the command line arguments */
  parseArguments( argc, argv,&files);
}

解析.c

#include <stdlib.h>
#include "stddef.h";
#include <stdlib.h>
#include <argp.h>

char* printUsage();
extern int parseArguments(int argc, char *argv[], char *files[]) {
  int i = 1;
  int amtFiles = 0;
  /** Loops through each item turning on and off switches*/
  while (argc > 1) { /* i moves left to right 0 is file name so start at 1*/

      if (isFile(argv[i]) == 1) { /*if its a file */
        *files = realloc(files, amtFiles * sizeof *files);
        *files[amtFiles] = argv[i];
        /*printf("%s",*files[amtFiles]);*/
        amtFiles++;
      }

    }
    i++;/* increment argv[i] to next inputted char*/
    argc--; /* decrement the total amount of arguments to go through */

  }/*Loop ends */

}

我假设它是一个指针错误,但由于我是 C 新手并且指针仍然有点混乱,所以很难弄清楚它。如果您还可以提供链接或解释,将不胜感激。

【问题讨论】:

  • *files = realloc(files, amtFiles * sizeof *files); 真是一团糟!
  • 看看你正在重新分配什么以及你将返回分配给什么。 *filesfiles 不是一回事。绘制图表可能会有所帮助。
  • 格式有所改进,但{ 仍然在某处丢失 - 或者编码了额外的}。缺少返回值
  • *files = realloc(files, amtFiles * sizeof *files); 中的大小错误,因为编码目标对我来说并不明显,所以不清楚如何纠正。
  • @chux 可能缺少一个我只是快速修剪我的代码来举个例子,我的目标是在 main 中创建列表,但能够在 parse.c 中根据需要重新分配它。它最终将是一个存储在 main 中的文件名列表,但我永远不知道将使用多少个文​​件

标签: c arrays pointers malloc realloc


【解决方案1】:

在您的主文件中是一个 char **(并且您传递了它的地址,因此参数实际上是一个 char ***)但 parseArguments 只需要一个 char*[]。

添加一个原型 在你的主文件中是一个 char **(并且你传递了它的地址,所以参数实际上是一个 char ***) nut parseArguments 只需要一个 char*[]。在 main.c 中,编译器会告诉你这个。我怀疑这是你的主要是正确的,但我没有通过代码解析来确保这一点。

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2021-03-11
    • 2016-06-27
    相关资源
    最近更新 更多