C列出正在释放的对象的错误校验和

时间:2018-01-02 20:23:45

标签: c

我正在尝试为调整大小数组编写C Struct并收到错误:

a.out(34254,0x7fffa17b7340) malloc: *** error for object 
0x7fdd39c02908: incorrect checksum for freed object - object was 
probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
[1]    34254 abort      ./a.out

这是我目前的代码:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>

typedef struct List {
    int length;
    int *vals; // This should be generic somehow
    int curr_inserted;
    int max_allowed; 
} List; 

List *initialize(int val) {
    List *curr; 
    curr = malloc(5 * sizeof(int));
    if (curr == NULL) {
        printf("Memory Allocation Error\n");
        exit(1);
    } else {
        curr->length = 1; 
        curr->vals = malloc(10 * sizeof(int));
        curr->vals[0] = val; 
        curr->curr_inserted = 1; 
        curr->max_allowed = 10; 
    }
    return curr; 
}
void add(List *x, int val) {
    if (x->curr_inserted == x->max_allowed) {
        int* bigger_arr = realloc(x->vals, (2 * x->max_allowed));
        x->vals = bigger_arr;
        x->max_allowed *= 2;
    }
    x->vals[x->curr_inserted] = val; 
    x->length++;
    x->curr_inserted++;
}

我正在初始化并检查这样的值:

int main() {
    List *x = initialize(10);
    for (int i = 0; i < 100; i++) {
        add(x,i); 
    }
    for (int i =0; i < x->length; i++) {
        printf("val %d is %d\n",i,x->vals[i]);
    }
    free(x);
    return 0; 
}

我认为错误是在我尝试调整大小的add方法中,但我无法弄清楚如何处理此错误。

1 个答案:

答案 0 :(得分:6)

int* bigger_arr = realloc(x->vals, (2 * x->max_allowed));

将是

int* bigger_arr = realloc(x->vals, (2 * x->max_allowed*sizeof(int)));

但是realloc的方式是错误的,因为realloc也可能失败。在分配之前,您应该检查它返回的内容。

同样curr = malloc(5 * sizeof(int)); curr = malloc(sizeof(List));因为 for strutures,您无法通过添加单个成员元素的大小来计算所需的已分配内存。总是有可能有填充,在这种情况下它会失败。