c - 为什么 Malloc 分配的内存比我请求的多?

标签 c arrays pointers struct malloc

我必须定义一个动态结构数组。但是当我这样定义数组时:

#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
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

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

关于c - 为什么 Malloc 分配的内存比我请求的多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906312/

相关文章:

c - 在C中按结构排序数组

最终赋值的 C 循环优化帮助(禁用编译器优化)

c - 如何将文件中的单词分配给 C 中的二维字符串数组

c - 我应该在这段 C 代码中使用指针吗?在哪里?

c++ - std::multiset 为插入和比较定义比较器

c - TCP套接字: Server/Client code structure

c++ - C++初始化二维数组

c++ - 使用 lambdas 初始化多维数组

c - 将 int 相除并存储回原始变量

c - “连接”一个结构到一个字符数组