【发布时间】:2014-01-24 15:48:27
【问题描述】:
我在 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 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-Line 1199 是 if (strcmp(command, "thing_to_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
我完全不知道问题出在哪里。
亲切的问候 菲利普
【问题讨论】:
-
它说问题出在一个名为
commandHandler的函数中。如果您不向我们展示该功能,您如何期望我们对该功能说任何合理的话? -
对不起,我忘记了 commandHandler。我编辑了帖子。
-
command为 NULL,即错误。在 C 中没有像引用调用那样的东西。您将 command 的值发送给函数,如果它在那里被更改,它是一个本地副本,而不是原始变量。
标签: c malloc valgrind pass-by-reference