Valgrind读取大小无效1

DMc*_*888 5 c valgrind

对于我的生活,我无法解决为什么我得到一个invalid read size of 1这个代码片段,我很确定它与我有关虐待char *url pointer...

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;    
}
Run Code Online (Sandbox Code Playgroud)

我得到的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
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*her 8

这里

char *url = malloc((length+1)*sizeof(char));
url = '\0';
strncat(url, space, length);
Run Code Online (Sandbox Code Playgroud)

你立刻通过设置失去了malloc内存urlNULL.注意,它'\0'是0,这是一个空指针常量.然后你尝试strncat一些无效的内存位置.

你可能想要设置

*url = '\0';
Run Code Online (Sandbox Code Playgroud)

那里.