【问题标题】:Can't reallocate memory of an array of structs (invalid next size) [duplicate]无法重新分配结构数组的内存(下一个大小无效)[重复]
【发布时间】:2014-01-23 03:10:27
【问题描述】:

我正在尝试重新分配结构数组 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);
}

【问题讨论】:

    标签: c struct glibc realloc


    【解决方案1】:

    以下内容正在破坏你的记忆

    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);
    

    很高兴inputsize_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);
    

    【讨论】:

      猜你喜欢
      • 2013-09-16
      • 1970-01-01
      • 2014-05-18
      • 2011-08-13
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2011-02-25
      • 2012-10-31
      相关资源
      最近更新 更多