Writing a program in which I need to split strings from a struct linked list into pieces and recombine them. I then insert the new Strings back into the Linked List.
the struct I am using to build the nodes looks like this:
typedef struct CANDIDATENODE
{
char sentence[TARGET_LEN+1];
int rank;
int score;
int goodFlag;
struct CANDIDATENODE *next;
} Candidate;
(TARGET_LEN is the maximum string length. not Including the null terminator, which is the reason for the +1 in )
I encounter no segfaults or bus errors, but after the third character is copied, the next time through my string arrays are filled with characters that do not belong.
earlier in the program I fill 20 nodes in a linked list with random characters. It is from this list of Nodes that I am passing in the Candidate pointer
The clearPointer below points to the end of the linked list where I will be adding the new sentences.
Here is the Problem method in its entirety.
void breedSentences(Candidate *can1)
{
Candidate *can2 = can1->next;
char childOne[TARGET_LEN+1];
char childTwo[TARGET_LEN+1];
memset(childOne, '\0', sizeof(TARGET_LEN+1));
memset(childTwo, '\0', sizeof(TARGET_LEN+1));
printf("parent1:%s;\n", can1->sentence);
printf("parent2:%s;\n", can2->sentence);
int pivot1 = random() %TARGET_LEN-1;
int pivot2 = random() %TARGET_LEN-1;
printf("pivot1= %d\n", pivot1);
printf("pivot2= %d\n", pivot2);
int i;
for (i =0; i<TARGET_LEN-1; i++)
{
if (i<pivot1)
{
childOne[i]= can1->sentence[i];
}
else
{
childOne[i]= can2->sentence[i];
}
if (i<pivot2)
{
childTwo[i]= can1->sentence[i];
}
else
{
childTwo[i]= can2->sentence[i];
}
childOne[TARGET_LEN]= '\0';
childTwo[TARGET_LEN]= '\0';
printf("First:%c\n", can1->sentence[i]);
printf("Second:%c\n", can2->sentence[i]);
printf("1:%s\n", childOne);
printf("2:%s\n", childTwo);
}
printf("%s\n", childOne);
printf("%s\n", childTwo);
strcpy(clearPointer->sentence, childOne);
clearPointer = clearPointer->next;
strcpy(clearPointer->sentence, childTwo);
clearPointer = clearPointer->next->next;
}
Wiz’s comment under my question led me to the answer. making my allocated space too small caused my program to behave unexpectedly.