[英]Why does `g_array_append_val` segfault when the element size is bigger than the actual value size?
My program segfaulted in a code that looks like the following: 我的程序出现以下代码段错误:
user_t user;
users = g_array_sized_new(FALSE, TRUE, sizeof(*user), nb_results);
g_array_append_val(users, user);
At line 3, instead of adding user by value I add it by pointer. 在第3行,不是通过值添加用户,而是通过指针添加了它。 This will segfault sometime.
这将在某些时候出现段错误。 The correct does initialize the
GArray
to host pointers: 正确的
GArray
是将GArray
初始化为托管指针:
users = g_array_sized_new(FALSE, TRUE, sizeof(user_t *), nb_results);
g_array_append_val(users, user);
I don't understand why the first version of this code does segfault since sizeof(*user)
is bigger than sizeof(user_t *)
. 我不明白为什么此代码的第一个版本会进行段错误,因为
sizeof(*user)
大于sizeof(user_t *)
。
For simplicity's sake, lets say that sizeof *user
is six bytes, and a pointer is four bytes. 为了简单起见,可以说
sizeof *user
是六个字节,而指针是四个字节。 That means an array of two users have 12 bytes, enough space for three pointers. 这意味着两个用户组成的数组有12个字节,足够用于三个指针的空间。 But when you get an element from that array it will get a six-byte element, which will contain one and a half pointer.
但是,当您从该数组中获取一个元素时,它将获得一个六字节的元素,其中将包含一个半指针。
When you try to store this value into a pointer, you will get half of the first pointer and half of the other pointer. 当您尝试将此值存储到指针中时,将获得第一个指针的一半和其他指针的一半。 That will not be valid and when you dereference it you will get undefined behavior .
那将是无效的,并且当您取消引用它时,将得到未定义的行为 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.