This question already has answers here:
I can use more memory than how much I've allocated with malloc(), why?
(17个答案)
5年前关闭。
我希望从此代码中看到编译错误,并且可能在运行可执行文件时看到错误。根据我的理解,如果在堆中分配了一个指针并存在该指针,并且malloc为该指针保留了空间,如果放置在指针上的空间太大,则应该开始覆盖代码空间。但是,这在Linux 64位Ubuntu 14.04上运行没有问题。
在此示例中,我最初保留5个字节,但在该内存地址放置21个字节(\ 0将为字节21?)。该程序运行没有问题,并且编译器未引发任何错误。
我使用以下命令进行了编译:“ gcc -Wextra -pedantic test.c -o test”
(17个答案)
5年前关闭。
我希望从此代码中看到编译错误,并且可能在运行可执行文件时看到错误。根据我的理解,如果在堆中分配了一个指针并存在该指针,并且malloc为该指针保留了空间,如果放置在指针上的空间太大,则应该开始覆盖代码空间。但是,这在Linux 64位Ubuntu 14.04上运行没有问题。
在此示例中,我最初保留5个字节,但在该内存地址放置21个字节(\ 0将为字节21?)。该程序运行没有问题,并且编译器未引发任何错误。
我使用以下命令进行了编译:“ gcc -Wextra -pedantic test.c -o test”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str;
/* Initial memory allocation */
str = malloc(5);
strcpy(str, "12345678901234567890");
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);
}
最佳答案
Malloc将返回一个大于5个字节的块。我猜测它会在实现上发生变化,但Google快速搜索会显示16个字节。
我不希望编译器产生编译错误(尽管可能是警告?)