簡體   English   中英

Valgrind讀取大小無效1

[英]Valgrind Invalid read size of 1

對於我的生活,我無法解決為什么我的這個代碼片段的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;    
}

我得到的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

有人可以指出我正確的方向嗎?

這里

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

你通過將url設置為NULL立即丟失malloced內存。 注意'\\0'是0,這是一個空指針常量。 然后你嘗試strncat到無效的內存位置。

你可能想要設置

*url = '\0';

那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM