[英]Why does the malloc order matter when a struct is sufficiently sized?
我今天遇到了一个有趣的问题。 此代码段打印垃圾(例如?Y@??
):
typedef struct {
int field_1;
int field_2;
int field_3;
char *arr[64];
} test;
int main(void) {
test *test = malloc(sizeof(test));
char *str = malloc(sizeof(char) * 6);
strncpy(str, "hello", 5);
str[5] = '\0';
test->arr[0] = str;
printf("%s\n", test->arr[0]);
}
但是,将test
更改为:
typedef struct {
int field_1;
int field_2;
char *arr[64];
} test;
(删除field_3
)打印预期结果( hello
)。
更奇怪的是,像这样交换malloc
调用:
char *str = malloc(sizeof(char) * 6);
test *test = malloc(sizeof(test));
无论test
的大小如何,都会打印正确的结果。
这到底是怎么回事?
我正在使用clang-1200.0.31.1
。
问题出在这一行:
test *test = malloc(sizeof(test));
这里, sizeof(test)
指的是名为test
的变量,而不是名为test
的类型。 所以你得到的是指针的大小,而不是结构的大小。 结果,您没有为有问题的对象分配足够的空间,并且写入超过了分配内存的末尾,调用了未定义的行为。
为 typedef 或变量指定不同的名称,例如:
typedef struct {
int field_1;
int field_2;
int field_3;
char *arr[64];
} test_type;
...
test_type *test = malloc(sizeof(test_type));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.