我期望看到編譯錯誤從這個代碼,並可能在運行可執行文件時出現錯誤。根據我的理解,如果一個指針被分配並存在於堆中,並且malloc爲指針保留空間,如果放置在指針處的內容太大,它應該開始覆蓋代碼空間。但是,這在Linux 64位Ubuntu 14.04上沒有問題。Malloc分配太少的空間,但代碼編譯和運行沒有錯誤
在這個例子中,我最初保留了5個字節,但是在這個存儲器地址上放了21個字節(\ 0將是字節21?)。該程序運行沒有問題,編譯器不會引發錯誤。
我使用命令編: 「GCC -Wextra -pedantic test.c的-o測試」
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str;
/* Initial memory allocation */
str = malloc(5);
strcpy(str, "123456789");
printf("String = %s, Address = %p\n", str, str);
/* Reallocating memory */
str = realloc(str, 26);
strcat(str, "12345");
printf("String = %s, Address = %p\n", str, str);
free(str);
return(0);
}
您的代碼中存在未定義的行爲。它完美運作的原因是純粹的運氣。意味着任何事情都可能發生。 – 2014-11-23 05:40:01