尺寸爲我的生活,我不能明白爲什麼我對這個代碼片斷得到一個invalid read size of 1
,我敢肯定它得到的東西與我濫用char *url pointer
...Valgrind的無效讀1
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
有人可以「點」嗎?
您爲url分配內存,然後將其設置爲空指針。 (url ='\ 0';)你的意思是,也許,設置url [0] ='\ 0'; ? – Joe 2012-02-24 02:56:39
你也許只想使用strncpy? – Cascabel 2012-02-24 02:58:18
你的前兩個'malloc'調用也有內存泄漏,它們本身完全是假的,你爲什麼要保留'sizeof''char' *指針*的大小呢?你的第三個'malloc'也顯示出可能出現混淆的跡象:(1)根據定義,不會拋出malloc的返回,這隻會隱藏錯誤(2)sizeof(char)'是'1'到'malloc'是你想要分配的'char'的數量。 – 2012-02-24 07:23:33