简体   繁体   English

为什么当元素大小大于实际值大小时,`g_array_append_val`会出现段错误?

[英]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.

相关问题 glib g_array_append_val()表现奇怪 - glib g_array_append_val() acting strange 为什么连接和复制大于数组大小的字符串没有错误? - Why no error in concatenating & copying strings bigger than array size? 初始化具有显式大小的char数组并初始化为大于该大小 - Initializing a char array with an explicit size and initialized to bigger than the size 为什么数组的元素大于类型? - Why is an element of an array bigger than the type? C-如果元素的索引大于动态分配的数组大小,它将返回null吗? - C- If index of element bigger than dynamically allocated array size, will it return null? 为什么qsort()需要知道数组的长度和数组元素的大小? - why does qsort() need to know the length of an array and the size of the array element? segfault分配char数组的大小 - segfault on allocating size for a char array 给数组更大的值不会增加数组的大小吗? - Giving array a bigger value doesn't increase its size? realloc()问题:旧块的释放,旧大小的旧大小,以及传递静态数组基址 - realloc() issues: deallocation of old block,new size bigger than old size,and passing static array base address SDL2窗口大小应该大于它 - SDL2 window size is bigger than it should be
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM