-1
所以我試圖輕鬆分配,然後釋放分配的內存,但valgrind寫入這些錯誤。分配時無效的讀/寫大小
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char* area=(char*)malloc(3);
strcpy(area, "lal");
printf("%s\n",area);
free(area);
return 0;
}
Invalid write of size 4
==2728== at 0x10873A: main (in /home/david/po1/a.out)
==2728== Address 0x5200040 is 0 bytes inside a block of size 3 alloc'd
==2728== at 0x4C2CB3F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2728== by 0x108731: main (in /home/david/po1/a.out)
==2728==
當一個字符串用雙引號引起來時,例如他在'strcpy(area,「lal」);' – ron
'strcpy()'實際上總是會複製空終止符,因爲它使用空終止者知道何時停止複製!正因爲如此,使用'strcpy()'通常被認爲是不安全的。 –
@AndrewDunn如果你先檢查長度或知道長度,那麼它是完全安全的 –