无法重新分配结构数组的内存(下一个大小无效)

时间:2014-01-05 18:54:22

标签: c struct glibc realloc

我正在尝试重新分配一个结构数组abcd_S但是编译器给了我

*** glibc detected *** realloc(): invalid next size: 0x0000000000603010 ***

我想重新分配数组,以便在重新分配后没有空字段。 另外,你认为我应该在哪里返回或退出该计划?

typedef struct abcd {
    char *first_field;
    char *second_field;
} abcd_S* struct_ptr;

abcd_S* read(int* array_size_ptr){

    abcd_S* tmp = NULL;
    int j=0,i;
    size_t input_len;
    struct_ptr =(abcd_S*)malloc(sizeof(abcd_S));

    if (struct_ptr == NULL) {
        printf("Error: Memory can't be allocated.\n");
    }
    else {
        do {
        scanf(format_specifier, input);
        if (strcmp(input,"A") != 0){
            j++;
            if (j == (*array_size_ptr)) {
                struct_ptr =(abcd_S*)realloc(struct_ptr, 2 * sizeof(abcd_S));
                if (struct_ptr == NULL) {
                    printf("Error: Memory can't be allocated.\n");
                    //return((COULDNT_ALLOCATE));
                }
                *size_ptr = (*size_ptr) * 2; //This needs to be done every time array is full
            }
            input_len = strlen(input);
            struct_ptr[j-1].first_field=(char *)malloc(input_len);
            if (struct_ptr[j-1].first_field == NULL) {
                printf("Error: Memory can't be allocated.\n");
                //return(COULDNT_ALLOCATE);
            }
            strcpy(struct_ptr[j - 1].first_field, input);

        }
        else {
            abcd_S*tmp = (abcd_S*)realloc(struct_ptr, j * sizeof(abcd_S));
            if (tmp == NULL){
                printf("Could not reallocate\n");
            }
        }        
    }while (strcmp("A",input) != 0);
    return(struct_ptr);
}

1 个答案:

答案 0 :(得分:0)

以下是破坏你的记忆

input_len = strlen(input);
struct_ptr[j-1].first_field=(char *)malloc(input_len);
...
strcpy(struct_ptr[j - 1].first_field, input);

相反,为'\0'

分配+1
input_len = strlen(input);
struct_ptr[j-1].first_field=(char *)malloc(input_len + 1);
...
strcpy(struct_ptr[j - 1].first_field, input);

很好,input属于size_t类型 此外,不需要演员表,因为你知道长度,为什么不能更快memcpy()

input_len = strlen(input);
struct_ptr[j-1].first_field = malloc(input_len + 1);
...
memcpy(struct_ptr[j - 1].first_field, input, input_len + 1);