我必须定义一个动态结构数组。但是当我这样定义数组时:
#include <stdio.h>
#include <stdlib.h>
struct user {
int id;
char *name;
int *friendlist;
int *blocklist;
char *university;
int age;
};
int main (void)
{
struct user *Userlist;
Userlist = malloc(sizeof(Userlist) * 10);
Userlist[2815].name="Someone";
printf("%s\n", Userlist[2815].name );
return 0;
}
我为 10 个用户列表结构定义了内存。它存储2815结构。但是当我尝试为第 2816 个结构赋值时,它显示“段错误。核心已转储”。它必须存储我分配的10个结构体,但为什么它存储2815个结构体?
最佳答案
malloc
调用仅预留您指定的存储空间(struct user
的 10 个元素)。 C 不对数组访问进行任何边界检查;该语言假设您知道数组有多大,并且您足够聪明,不会超出数组的末尾。
尝试访问超出数组末尾的项目会调用未定义的行为,这不会导致段错误或崩溃。碰巧的是,索引 2815 处的内存没有受到保护,也没有被用于任何“重要”的事情(尽管它可能会影响其他地方的执行)。
作为引用,以下是“未定义行为”的定义,取自 the latest standard :
3.4.3
1 undefined behavior
2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). 3 EXAMPLE An example of undefined behavior is the behavior on integer overflow
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
关于c - 为什么 Malloc 分配的内存比我请求的多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906312/