Question

I'm trying to reallocate an array of structs abcd_S but compiler gives me

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

I want to reallocate the array so that there are no empty fields after the reallocation. Also, where do you think i should return or exit the program?

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);
}
Was it helpful?

Solution

The following is corrupting your memory

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

Instead, allocate +1 for the '\0'

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

Nice that input is of type size_t.
Further, the cast is not needed and since you know the length, why not the faster 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top