The first line here is a basically NOOP (actually it is creating a memory leak because you throw away the pointer returned by malloc
by overwriting it on the next line).
lines[i] = (char*)malloc(sizeof(char)); // this is a basically a NOOP
lines[i] = result;
It's more or less like writing:
foo = 5;
foo = result;
So your code ends up like this:
for (i = 0; i < 100; i++)
{
char temp[10];
_itoa_s(i, temp,10);
char result[10] = "test";
strcat_s(result, temp);
lines[i] = result; // copying just the pointer,
}
So all lines[i]
contain the pointer to the same memory location result
.
Also the scope of result
is limited to the part between {}
, so once the for
loop is terminated, result
is likely to be overwritten at the next occasion.
You need this:
char *lines[100];
for (int i = 0; i < 100; i++)
{
char temp[10];
_itoa_s(i, temp,10);
char result[10] = "test";
strcat_s(result, temp);
lines[i] = (char*)malloc(sizeof(char) * strlen(result) + 1);
// ^string length ^space for NUL terminator
strcpy(lines[i], result); // actually copying the the string (not only the pointer)
}
You also need to free the allocated memory once you're done with it:
for (i = 0; i < 100; i++)
{
free(lines[i]);
}