c - 在 char 数组上使用 'free' 时出错

标签 c arrays pointers char free

我是 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 的行。我假设您正在调用:

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);

关于c - 在 char 数组上使用 'free' 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32730927/

相关文章:

c - 数组如何在结构中工作?

c - 获取结构体数组内结构体的值

c - 嵌入IO语言: Call Io method from C

c - (Android NDK) 包含非 ASCII 字符的字符串被截断

php - 来自数据库查询的数组内数组

c++ - 从其行和列的给定总和生成一个二维整数数组

c - 删除从循环调用的函数中的 switch-case

PHP 的 current() 和 key() 函数;与函数签名不一致

c++ - C++ 中的引用更新

c++ - 非递归删除二叉树的问题