int n = 0;
char s[] = "I am a college student, I live in Vietnam";
char **a = NULL;
char **temp = NULL;
char* pc = strtok(s, ",");
while (pc)
{
n++;
temp = (char**)realloc(a, n * sizeof(char*));
if (temp)
{
a = temp;
free(temp);
temp = NULL;
}
else
{
for (int k = 0; k < n; k++)
{
free(a);
a = NULL;
}
free(*a);
*a = NULL;
}
a[n - 1] = (char*)malloc((strlen(pc) + 1) * sizeof(wchar_t));
strcpy(a[n - 1], pc);
a[n - 1][strlen(pc)] = '\0';
pc = strtok(NULL, ",");
}
for (int i = 0; a[i]; i++)
{
free(a[i]);
a[i] = NULL;
}
free(*a);
*a = NULL;
In while loop. I used realloc to allocate with each element is char*. It worked normally when I allocated first element. But in the second times when I allocated "I live in Vietnam".
temp = (char**)realloc(a, n * sizeof(char*));
It has triggered a breakpoint. Realloc does copy all the data when it reallocate, so it must have copied "I am a college student". Why's this error happened?
And after that. In freeing memory part. I haven't tried but it must be something wrong here. I haven't figured it out. Thank you for helping me