Dav*_*uez 1 c arrays free pointers char
我是 C 的新手,并试图用它编写一个命令行程序。我正在尝试在程序终止之前释放一个字符数组。但是当它到达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.
Run Code Online (Sandbox Code Playgroud)
我的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;
}
Run Code Online (Sandbox Code Playgroud)
所以在程序的其余部分结束后,我希望能够释放在getInput()
函数中分配的内存。我在想我input
返回字符指针的方式正在搞砸。但我不确定如何修复它。任何帮助表示赞赏。
您尚未发布调用free
. 我假设你正在打电话:
free(input);
Run Code Online (Sandbox Code Playgroud)
我明白为什么这会是一个问题。
您正在更改input
以下行中的值:
for (j = 0; j <= i; j++)
input++;
Run Code Online (Sandbox Code Playgroud)
当你打电话free
时,指针的值必须什么被退回malloc
,calloc
或realloc
。如果您使用任何其他指针值,程序将受到未定义行为的影响。
确保保留返回的值,以便您可以调用free
使用它。
char* input = getInput();
char* saved_ptr = input;
// ...
// Change input
// ...
// Deallocate memory using the original pointer
free(saved_ptr);
Run Code Online (Sandbox Code Playgroud)