【发布时间】: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