简体   繁体   中英

C - Self-referencing structure and realloc

I've got a problem with calling realloc on self-referencing structure. When I run this program, I get error *** Error in ...: realloc(): invalid next size: 0x0000000000602160 *** . I suppose the problem is related to the last line, because program runs without any problem if I comment it.

This is the smallest (not) working piece of code:

#include <string.h>
#include <stdlib.h>

typedef struct structure {
    int connections;
    struct structure *links;
} structure;

int main(int argc, char *argv[]) {
    int struct_count;
    int i, from, to, offset;
    structure *structs;

    struct_count = 2;

    structs = malloc(sizeof(structure) * struct_count);
    memset(structs, 0, sizeof(structure) * struct_count);
    for(i = 0; i < struct_count; i++) {
        structs[i].links = malloc(1);
        structs[i].connections = 0;
    }

    for(i = 0; i < 100; i++) {
        from = 0;
        to = 1;

        offset = structs[from].connections++;
        structs[from].links = realloc(structs[from].links, sizeof(int) * (offset + 1));
        structs[from].links[offset] = structs[to]; // This is the problematic line - why?
    }
}

And my question: what's wrong in that code?

The problem is the first time you allocate it, it's not enough. To allocate n elements of a given type you can use

structs[i].links = malloc(n * sizeof(*structs[i].links));

and the same goes wit realloc() you also need to make sure that realloc() doesn't return NULL , suppose that after allocating space for n structures with the line above you want to resize to store n + 1 instances, then

struct structure *links;
links = realloc(structs[i].links, (n + 1) * sizeof(*links));
if (links == NULL)
{
   /* Depending on the way your program is designed */
   probably_free_links(&structs[i].links);
   /*                  ^ make it `NULL' inside */
   allocation_failure_do_something_about_it_but_do_not_continue();
}
structs[i].links = links;

you can make structs[i].links = NULL; initially and realloc() will behave as malloc() the first time.

Write your programs as if all errors are possible, and do something about them don't just let your program invoke undefined behavior and make it a mistery to you and your program users.

If You will increase the Blueprint of structure and decrease the size of loop it will run perfectly..

**For Example:-**without manipulating run your program just decrease the loop condition from 100 to 2. It will run perfectly.

If you want to increase loop size you have to increase the size of structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM