【问题标题】:Error using 'free' on char array在 char 数组上使用“免费”时出错
【发布时间】:2015-12-20 06:15:36
【问题描述】:

我是 C 新手,正在尝试用它编写命令行程序。我试图在程序终止之前释放一个 char 数组。但是当它到达free 命令时,我收到“调试断言失败”运行时错误。在到达该点之前,程序会删除该数组中的字符,直到第一个空格。我在数组上使用了递增技术,因为我读到这是一种从数组中逐个删除字符的方法。这是这段代码:

char command[140];
char * input = getInput();  //prompt function for user input

//get string up to first whitespace to separate the command and its parameters
for (i = 0; i < strlen(input); i++)
{
    if (input[i] == ' ' || input[i] == '\0')
        break;

    command[i] = input[i];
}

for (j = 0; j <= i; j++)    //removes command and space and leaves parameters
    input++;

command[i] = '\0';  //null terminate char array
numParams = getNumParams(input);
free(input);  //should've added this line earlier to avoid confusion.

我的getInput() 函数是这样做的:

char * getInput()
{
    int n, size = 260;
    char * input = (char*)malloc(size);
    if (!input)                 //make sure memory allocation worked
        return NULL;

    do
    {
        printf("cmd> ");            //prompt
        fgets(input, 256, stdin);   //get user input/commands
        n = strlen(input);
    } while (n <= 1);

    if (input[n - 1] == '\n')           //remove new line from input array
        input[n - 1] = '\0';

    return input;
}

所以在程序的其余部分结束后,我希望能够释放在getInput() 函数中分配的内存。我在想我让input 返回一个 char 指针的方式搞砸了。但我不知道如何解决它。任何帮助表示赞赏。

【问题讨论】:

  • 你在哪里打电话给free

标签: c arrays pointers char free


【解决方案1】:

您尚未发布调用free 的线路。我假设您正在调用:

free(input);

我明白为什么这会是个问题。

您正在更改以下行中input 的值:

for (j = 0; j <= i; j++) 
    input++;

当您调用free 时,指针的值必须是malloccallocrealloc 返回的值。如果您使用任何其他指针值,程序会受到未定义行为的影响。

确保保留返回的值,以便您可以使用它调用free

char* input = getInput();
char* saved_ptr = input;

// ...
// Change input
// ...    

// Deallocate memory using the original pointer
free(saved_ptr);

【讨论】:

    【解决方案2】:

    问题最有可能这两行:

    for (j = 0; j <= i; j++)    //removes command and space and leaves parameters
        input++;
    

    在此处修改指针,使您失去应该传递给free 的原始指针。您需要将原始指针保存在临时变量中,并将其传递给free

    【讨论】:

      【解决方案3】:

      因为您在此处修改 input 指针而收到错误:

      for (j = 0; j <= i; j++)    //removes command and space and leaves parameters
          input++;
      

      此操作后,input 不再指向内存的开头,由malloc 分配。从而给你错误。而是将input 复制到另一个指针变量。

      此外,请考虑在 getInput() 之外进行分配,因为如果可能的话,在同一函数中分配和释放内存被认为是一种很好的做法。

      【讨论】:

      • 我是在循环之前还是之后进行复制?
      • 之前,保持原值
      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多