如何解决当结构足够大时,为什么malloc顺序很重要?
我今天遇到了一个有趣的问题。该代码段会打印垃圾(例如?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
的类型。因此,您得到的是指针的大小,而不是结构的大小。结果,您没有为有问题的对象分配足够的空间,而是在分配的内存末尾写入,从而调用undefined behavior。
为typedef或变量赋予不同的名称,例如:
typedef struct {
int field_1;
int field_2;
int field_3;
char *arr[64];
} test_type;
...
test_type *test = malloc(sizeof(test_type));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。