Strange behavior by setting NULL in array

Solution 1:

All your allocations are wrong.

First of all you want to create an array of 8 elements, so the first allocation should be

char **_pars = malloc(8 * sizeof *_pars);

Or if you want the array to be terminated by a null-pointer you need to allocate 9 elements (exchange the 8 for a 9 above).

Secondly the size returned by snprintf does not include the null-terminator, so all your calls

_pars[i] = malloc(tmp[i]);

should be

_pars[i] = malloc(tmp[i] + 1);

to fit the null-terminator.


On another note, all your code could be simplified quite a lot if you put all the x values in an array:

int exes[8] = { x, x2, x3, x4, x5, x6, x7 };

Because then you could use loops for all repetitive code:

for (unsigned i = 1; i < 8; ++i)
{
    tmp[i] = snprintf(NULL, 0, "%d", exes[i]);
}