My code gives me segfault error: which I don’t understand,the debugger says error comes from printing the value from stored_
char *stored_ = NULL;
char testMessage[15];
//strcpy(stored_, testMessage);
for (int a = 0;a < 10; a++)
{
sprintf(testMessage,"Message::%i\n",a);
printf("string is:%s;length is %i\n",testMessage,strlen(testMessage));
stored_ = (char*) realloc (stored_, sizeof(char) * (strlen(testMessage) * (a+1) ));
strcpy(&stored_[a], testMessage);
}
for (int b = 0;b < 10; b++)
{
printf("inside:|%s|\n",stored_[b]);
}
Fist up,
sizeof(char)is always 1, you don’t need to multiply by it.Secondly, when you’re allocating room for a string, you have to use:
In other words, you need room for the null byte at the end.
Thirdly, you appear to be confused between character pointers and character pointer pointers.
stored_is a single block of characters andstored_[1]is only one byte beyondstored_[0], meaning you won’t have enough room to store the string.You’ll either have to manage the single block of characters yourself, leaving enough room for each element (by using sparse indexes), or have a block of character pointers with indexes 0, 1, 2 and so on, but you’ll then have to manage the string allocations separately.
The following code shows how to do this latter one:
That’s the meat of it, the allocation of the array of character pointers separate from the actual arrays of characters forming the C strings.
Then the code below prints them and cleans up.
The output being, as expected:
With this method, each cell is a pointer to an array of characters, separately allocated (which holds the C string):