malloc 是否保证只分配分配的内存块?

does malloc guarantee to allocate only the assigned memory block?

我在下面的程序中只为 4 个整数分配了内存,但是 compiled/built 和 gcc 7.4.0 的程序没有崩溃。是因为当我 运行 构建的 exe 时,分配的 4*4 字节旁边的内存没有被使用吗?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *p = malloc(4*sizeof(int)); //allocating for only 4 integers
    if(NULL != p)
    {
        p[0] = 13;
        p[1] = 24;
        p[2] = 35;
        p[3] = 46;
        p[4] = 57;
        p[76] = 67;
        p[100] = 32;
        printf("%d %d %d %d %d %d %d", p[0], p[1], p[2], p[3], p[4], p[76], p[100]); //no crash? why?
        free(p);
    }
    return 0;
}

当您读取或写入超过已分配内存的界限时,您会触发 undefined behavior

对于未定义的行为,C 标准不对您的程序将执行的操作做出任何保证。它可能会崩溃,可能会输出奇怪的结果,或者(如本例)它可能看起来工作正常。此外,进行看似无关的更改(例如添加未使用的局部变量或调用 printf 进行调试)可以改变未定义行为的表现方式,使用不同的优化设置进行编译也是如此。

仅仅因为程序可能崩溃并不意味着它将会

综上所述,malloc 的特定实现可以预留比请求更多的内存,但同样您不能依赖它。唯一的保证是您得到的字节数正是您要求的。