C - Malloc 内部函数 / 按引用调用 / Valgrind



我对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] = '';
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] = '';
return RETURN_SUCCESS;
}

命令处理程序行 1199if (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

我完全不知道问题出在哪里。

亲切问候 菲利普

getUserInput

无法改变command的值,因为所有函数在C中都是按值传递的。 因此,当你得到所有的strcmp函数时,你正在取消引用导致各种坏事的NULL指针。

如果你想让getUserInput能够改变command的值,你必须将command的地址传递给函数(这意味着函数必须接受一个char**参数)。

相关内容

  • 没有找到相关文章

最新更新