Valgrind读取大小无效1

时间:2012-02-24 02:51:10

标签: c valgrind

对于我的生活,我无法解决为什么我得到invalid read size of 1这段代码片段,我很确定它与我滥用char *url pointer ...有关。 / p>

char *extractURL(char request[])
{
char *space = malloc(sizeof(char *));
space = strchr(request, ' ')+1;
char *hostend = malloc(sizeof(char *));
hostend = strchr(request, '\r');
int length = hostend - space;
if (length > 0)
{
    printf("Mallocing %d bytes for url\n.", length+1);
    char *url = (char *)malloc((length+1)*sizeof(char));
    url = '\0';
    strncat(url, space, length);
    return url;
}
//else we have hit an error so return NULL
return NULL;    
}

我得到的valgrind错误是:

==4156== Invalid read of size 1

==4156==    at 0x4007518: strncat (mc_replace_strmem.c:206)

==4156==    by 0x8048D25: extractURL ()

==4156==    by 0x8048E59: processRequest ()

==4156==    by 0x8049881: main ()

==4156==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:8)

下面

char *url = malloc((length+1)*sizeof(char));
url = '\0';
strncat(url, space, length);

您可以通过将url设置为NULL来立即丢失malloced内存。请注意,'\0'为0,这是一个空指针常量。然后你尝试strncat某些内容到无效的内存位置。

你可能想要设置

*url = '\0';

那里。