malloc的有趣行为()

Ume*_*C G 0 c malloc pointers allocation

这是我为GCC编译器编写的代码.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p;
    p = (int *)malloc(9 * sizeof(char));
    p[0] = 2147483647;
    p[1] = 2147483647;
    p[2] = 1025;
    printf("%d, %d, %d, %d\n", sizeof(char), *(p), *(p+1), *(p+2));
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

1, 2147483647, 2147483647, 1025
Run Code Online (Sandbox Code Playgroud)

我的问题是,虽然我只为指针分配了9个字节,但它似乎使用了所有12个字节.结果是相同的(除非编译器警告),如果我转换(char *)而不是(int*).分配malloc()是完整的圆圈吗?即它总是以指针的数据类型的倍数分配,而不管我们分配的是什么?或者具体实施?

gio*_*gim 7

    p = (int *)malloc(9 * sizeof(char));
Run Code Online (Sandbox Code Playgroud)

如果整数的大小是4个字节,那么您正在做的是未定义的行为.因为你分配了9个字节并使用了12个字节

施放没有任何效果,实际上你根本不应该malloc在C中施放结果.

您触发未定义行为的另一个地方是使用错误的格式说明符sizeof,您应该使用%zu而不是%din printf(for sizeof).