I would like to hold a dynamic list of objects. I am not allowed to use VLAs, so I wrote the following function: (Originally this was a list of structs I defined, but I reproduced the same problem with strings.)
#include <stdlib.h>
#include <string.h>
void appendSeq(char ** seq, char *** seqList, size_t curSeqListSize) {
if (*seqList == NULL)
*seqList = (char **) malloc(sizeof(char *));
else
*seqList = (char **) realloc(*seqList, sizeof(char *) * (curSeqListSize + 1));
if (*seqList == NULL)
exit(EXIT_FAILURE);
*seqList[curSeqListSize] = *seq;
}
int main()
{
char *curSeq = "";
char ** seqList = NULL;
for (int i = 0; i < 3; i++)
{
curSeq = "Sequence";
char* curSeqCopy = strdup(curSeq);
appendSeq(&curSeqCopy, &seqList, i);
}
}
This fails with a segmentation error, and it seems that the realloc() function is not doing its job - Why?