Free() a safe-copied string array crashes?

50 views Asked by At

I am trying to run the following C program on an SoC platform (baremetal application).

I have a couple of string arrays, defined as

char *init_array[] = { "foo", "bar bar" }

I know this works as an array of char arrays : *init_array[0] returns the 'f' character, init_array[0] returns the first address of "foo" and &init_array[0] returns the adress where the first address of "foo" is saved. The program I work with is based on that definition, so I am not supposed to change it.

Those arrays are going into a loop, in which there may or may not occur an external alteration. At the following iteration, the array must not carry the 'error'.

One of the solutions I've got was to keep two copies of those arrays, the ones I'm gonna use and ones that will initialize them.

Obviously, this has to be "safe-copied", in order to avoid using the same addresses. I have achieved this, with the following code:

char *my_array[2];

for (int i = 0; i < 2; i++) {

        my_array[i] = malloc(strlen(init_array[i]) + 1);

        memcpy(my_array[i], init_array[i],
                strlen(init_array[i]) + 1);

    }

The use of malloc() here (which I would rather avoid, if it's possible) demands the use of free() at the end of every iteration:

for (int i = 0; i < 2; i++) {

// i know it crashes somewhere here

    free(my_array[i]);
    my_array[i] = NULL; //this is supposed to tackle the issue of the same pointer being freed twice(?)

And it works perfectly, for a small number of iterations. Then, the program crashes, and I have to reset the platform I'm working on. As I mention above, I know it crashes somewhere in the last loop. I've also read that:

Crashes in malloc(), calloc(), realloc(), or free() are almost always related to heap corruption, such as overflowing an allocated chunk or freeing the same pointer twice.

I really can't figure out what I'm doing wrong. Is this a heap corruption issue and how can I handle it or am I wrong from the start?

0

There are 0 answers