I'm trying to traverse through my linked list and combine each of the nodes fields into a string, and then add the string into an array of strings.
void listToArray(){
//create array of strings
char *list[numNodes];
int i = 0, n;
while(head != NULL){
// add string to array
printf("[%d] %s %s:%d\n ", i, head->fileName, head->ip, head->port);
n = sprintf(list[i], "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
head = head->next;
printf("%s\n", list[i]);
i++;
}
The printf statement works fine, which shows that it is not the fields of node that are causing the problem, but when I do my sprintf statement to copy the string into the index of the array. I get a segmentation fault.
list[i]char *list[numNodes];it allocates space for an array ofcharpointers, but they aren't initialized yet. You need to allocate them (e.g., usingmallocfor each element:for ( i = 0; i < numNodes; i++ ) list[i] = malloc(stringSize);).char temp[128];then sprintf into temp and then setlist[i] = strdup(temp);sprintf(), useasprintf()which will automatically allocate a memory large enough to hold the resulting string including the null byte terminator. However, this is a GNU extension, also available in *BSD, but not in POSIX.