malloc内部函数/引用调用/valgrind
我对C不是很专业,所以我对valgrind有问题 我想从命令行读取输入 如果我这样试的话,效果很好malloc内部函数/引用调用/valgrind,c,malloc,valgrind,pass-by-reference,C,Malloc,Valgrind,Pass By Reference,我对C不是很专业,所以我对valgrind有问题 我想从命令行读取输入 如果我这样试的话,效果很好 //call the function char *command = getUserInput(); //function char *getUserInput() { char *buffer = NULL; char *temp = NULL; unsigned int count = 0; unsigned int lenght = 10; char charac
//call the function
char *command = getUserInput();
//function
char *getUserInput()
{
char *buffer = NULL;
char *temp = NULL;
unsigned int count = 0;
unsigned int lenght = 10;
char character = 0;
buffer = malloc((lenght+1)*sizeof(char));
if(buffer == NULL)
{
// printf(ERROR_OUT_OF_MEM);
// return EXIT_OUT_OF_MEM;
}
while((character = getchar()) != '\n')
{
if(count == lenght)
{
lenght += 10;
temp = realloc(buffer,lenght*sizeof(char));
if(temp != NULL)
{
buffer = temp;
}
else
{
free (buffer);
// printf(ERROR_OUT_OF_MEM);
// return EXIT_OUT_OF_MEM;
}
}
buffer[count] = character;
count++;
}
buffer[count] = '\0';
return buffer;
}
但是我不能得到一个错误的返回值
如果我通过引用调用的方式尝试它,我会得到一些我不理解的valgrind错误。
我知道,在这个函数调用示例中,我不请求返回值
//call function
char *command = NULL;
getUserInput(command);
//function
int getUserInput(char *name)
{
char *temp = NULL;
unsigned int count = 0;
unsigned int lenght = 10;
char character = 0;
name = malloc((lenght+1)*sizeof(char));
checkMemory(name);
while((character = getchar()) != '\n')
{
if(count == lenght)
{
lenght += 10;
temp = realloc(name,lenght*sizeof(char));
if(temp != NULL)
{
name = temp;
}
else
{
free (name);
printf(ERROR_OUT_OF_MEMORY_MESSAGE);
return ERROR_OUT_OF_MEMORY;
}
}
name[count] = character;
count++;
}
name[count] = '\0';
return RETURN_SUCCESS;
}
Commandhandler行1199是if(strcmp(command,“thing\u to\u compare”)==0)
瓦尔格林:
==23886== Use of uninitialised value of size 4
==23886== at 0x40256BB: strcmp (mc_replace_strmem.c:426)
==23886== by 0x8049B39: commandHandler (assa.c:1199)
==23886== by 0x8049D6C: main (assa.c:1295)
==23886== Uninitialised value was created by a stack allocation
==23886== at 0x8049B00: commandHandler (assa.c:1189)
==23886==
==23886== Invalid read of size 1
==23886== at 0x40256BB: strcmp (mc_replace_strmem.c:426)
==23886== by 0x8049B39: commandHandler (assa.c:1199)
==23886== by 0x8049D6C: main (assa.c:1295)
==23886== Address 0x0 is not stack'd, malloc'd or (recently) free'd
我完全不知道问题出在哪里
问候
Philipp
getUserInput
无法更改command
的值,因为所有函数在C中都是按值传递的。因此,当您访问所有strcmp
函数时,您取消了对NULL
指针的引用,导致了各种各样的错误
如果希望
getUserInput
能够更改command
的值,则必须将command
的地址传递给该函数(这意味着该函数必须采用char**
参数)。它指出问题出在名为commandHandler
的函数中。如果您不向我们展示该函数,您希望我们如何对其做出合理的解释?对不起,我忘记了commandHandler。我编辑了帖子。命令
为空,这是错误。没有什么比C中的引用调用更好的了。您将command的值发送给函数,如果在那里更改了,它是一个本地副本,而不是原始变量。谢谢,所以现在我必须像这样传递值<代码>getUserInput(&command)代码>和函数int getUserInput(char**name)
?我不明白的是如何访问函数中的name
。将每个名称
更改为*名称
?如果我这样做,就会出现分段错误。当您分配单个字符时,您必须执行类似于(*name)[count]
的操作以保持操作顺序一致。