我正在尝试增加一个数组来添加新的malloc'd指针。 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*));
答案 0 :(得分:1)
我不知道为什么你会期望new_active_alloc_array_ptr
的大小改变,它是一个指针,并且总是具有相同的大小 - 指针的大小。
有很多错误都可能导致您的崩溃:
(1)如果您希望m61_state->sz + sizeof(ACTIVE_ALLOCATION*)
大小为m61_state->sz
的条目有足够的空间,那么您需要重新调整为sizeof(ACTIVE_ALLOCATION*)
,因此它应为m61_state->sz * sizeof(ACTIVE_ALLOCATION*)
。
(2)您似乎将realloc'd指针存储到临时(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
到0
访问大小为n-1
的数组中的元素,因此即使您已正确分配以创建大小为m61_state->sz
的数组然后[m61_state->sz]
仍会指向超出您已分配空间末尾的元素。