Why does realloc cause a segfault here?
I'm looking at this code, but I can't seem to figure out why it's segfaulting.
The purpose of the function is to put each period separated word (token) into a list that grows as large as necessary.
[Edit: Oh, uh, this is C89.]
Code:
#include <stdlib.h>
static int getdots(char* input, char** keylist) {
keylist = calloc(1, sizeof(char*));
int i = 0;
keylist[i] = malloc(512* sizeof (char));
memset(keylist[i],'\0', 512*sizeof(char));
char* p = input, *c=keylist[0];
while (*p!='\0') {
while(c && p)
if(*p!='.')
*c++=*p++;
else
break;
if(*p=='.')
{
i++;
keylist=realloc(keylist, sizeof(char*)*(i+1));
keylist[i]=malloc(512*sizeof(char));
c=keylist[i];
memset(keylist[i],'\0', 512*sizeof(char));
}
p++;
}
return 0;
}
int main() {
char input[512] = { "hello.helm.happy\0" };
char** keylist = NULL;
getdots((char*) &input, keylist);
if (!keylist) {
printf("Nothing happened!\r\n");
return 0;
}
int i = 0;
for (i = 0; keylist[i]; i++)
printf("%s\r\n", keylist[i]);
if (keylist != NULL)
free(keylist);
return 0;
}