c - memset 上的段错误

标签 c

我正在尝试增长一个数组以添加新的 malloc 指针。 realloc 似乎并没有增加大小。另外,我一开始就为数组中的一个指针提供了足够的空间,因此即使 realloc 没有增加大小,我仍然希望能够复制一个指针,但我得到了 SIGSEGV 段错误。

typedef struct active_allocation {
    size_t sz;
    void *ptr;
} ACTIVE_ALLOCATION;

struct m61_state {
    ACTIVE_ALLOCATION **active_allocations_ptrs_arr; //Array of Points to Active Allocations
    size_t sz;
};
struct m61_state m61_state;
...
ACTIVE_ALLOCATION **active_allocations_ptrs_arr = malloc(sizeof(ACTIVE_ALLOCATION*) *1); 
m61_state.active_allocations_ptrs_arr = active_allocations_ptrs_arr;
...
//Create a New pointer, to add to the array
ACTIVE_ALLOCATION *active_allocation_record = malloc(sizeof(ACTIVE_ALLOCATION));

// ** Initially there's space for one pointer, but it hasn't been used yet.  
//m61_state->sz equals 0.
//Trying to increase the size of an array to 8 for one more ACTIVE_ALLOCATION* Last 4 can be set to NULl
//sizeof(new_active_alloc_array_ptr) equals 4 at this point
new_active_alloc_array_ptr = realloc(m61_state->active_allocations_ptrs_arr, m61_state->sz + sizeof(ACTIVE_ALLOCATION*));

//** sizeof(new_active_alloc_array_ptr) still equals 4.  I want it to be 8. I'm not sure why the size didn't change.

//Copy the new pointer that was just created active_allocation_record to the array
memset(m61_state->active_allocations_ptrs_arr[sizeof(ACTIVE_ALLOCATION*)* m61_state->sz], (int)active_allocation_record, sizeof(ACTIVE_ALLOCATION*));

最佳答案

我不知道为什么您会期望 new_active_alloc_array_ptr 的大小发生变化,它是一个指针,并且始终具有相同的大小 - 指针的大小。

存在许多错误,所有这些错误都可能导致您的崩溃:

(1) 当您似乎需要足够的空间来容纳 m61_state->sz 时,您正在将大小调整为 m61_state->sz + sizeof(ACTIVE_ALLOCATION*)条目大小为 sizeof(ACTIVE_ALLOCATION*),因此应为 m61_state->sz * sizeof(ACTIVE_ALLOCATION*)

(2) 您似乎将重新分配的指针存储到临时 (new_active_alloc_array_ptr),然后访问原始 m61_state->active_allocations_ptrs_arr 值。

(3) 当您访问数组时,您正在访问的元素为 [sizeof(ACTIVE_ALLOCATION*)* m61_state->sz] - 没有调用 sizeof(ACTIVE_ALLOCATION* )* 这里应该是[m61_state->sz]

(4) 大小为 n 的数组中的元素是从 0n-1 访问的,因此即使您分配正确创建大小为 m61_state->sz 的数组,则 [m61_state->sz] 仍会指向超出您分配的空间末尾的一个元素。

关于c - memset 上的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686452/

相关文章:

c - OpenMP - for 循环线程分配

c - 为什么两个整数相除返回 0.00?

c - C11中的pthread_create函数

c - 如何在迷宫中找到最快的路线(C 语言)

c - 信息 C5012 : loop not parallelized due to reason '1008'

c - 类型转换 void 指针到 int 和 string

c# - 将带有 C 和 asm 代码的程序转换为 DLL

c - 将 0 表示为 gnss 坐标的负数

c - 编译 C(非 C++)OpenCV 代码时出现问题

c - 什么时候可以省略宏中参数周围的括号?