C 内存分配未按预期工作

C memory allocation not working as expected

我不熟悉处理指针和内存分配。我不明白我做错了什么。这是我的代码:

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

int main() {
     int* i;
     printf("Size of i:%d\n",sizeof(i));
     i = malloc(5 * sizeof(int));
     printf("Size of i:%d\n",sizeof(i));
     i[100] = 3;
     printf("Impossible i:%d\n",i[100]);
}

我使用gcc file.c编译它。根据我的理解,这不应该被编译,因为 i[100] 没有分配。相反,我得到一个输出:

Size of i:8
Size of i:8
Impossible i:3

我在这里错过了什么?忽略不可能的 i,根据我的理解,前两行的输出应该是

Size of i:8
Size of i:40

From my understanding, this should not have been compiled since i[100] is not allocated.

只是undefined behaviour访问越界。对于未定义的行为,编译器可能会也可能不会发出诊断。语言没有要求。

Disregarding the impossible i, to my understanding the output of the first two lines should have been

Size of i:8
Size of i:40

与数组不同,指针上的 sizeof 运算符无法推断出它所指向的内存块的大小。它总是会给出指针的大小,即 sizeof(i) == sizeof (int*)

无法从指针中推断出来;你只需要自己跟踪它。一种方法是将值 5 存储在变量中,如果 malloc 成功,您知道有 space 用于 5 个整数。