我有以下一段代码,我预计它会失败,但似乎工作正常。我很困惑为什么这不会导致某种段错误。
#include <stdio.h>
#include <stdlib.h>
struct entry {
int foo;
};
struct table {
int size;
struct entry* entries;
};
typedef struct table *Table;
typedef struct entry Entry;
int main() {
Table table = malloc(sizeof(struct table));
table->entries = malloc(sizeof(struct entry) * 1);
(table->entries)[5].foo = 5;
for (int i = 0; i < 10; i++) {
printf("Entry #%d: %d\n",i,(table->entries)[i].foo);
}
}
我本以为,因为我只为 table->entries 中的一个条目分配了足够的空间,所以访问 0 以外的任何索引都是越界的。但是当我运行这个程序时,它打印出 5 for 作为索引 5 处条目的 foo 值,其余打印为 0,这是正确的行为。为什么这没有失败?
最佳答案
别人会说得更好,但未定义的行为是未定义的。
没有定义。它可能会起作用。它可能不会。
这完全取决于那些内存位置中的内容。
你写了一个错误的位置。你读了一些其他的。你碰巧没有撞到任何东西 太重要了。
您写的一个字远远超出了您的分配区域。也许如果你做了更多的计算 那会引起麻烦,因为您写入了 malloc 的数据结构。也许不是。
关于c - 在 C 中分配数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106750/