I dont have any idea what the problem is. But what I know is it stopped at
fgets(temp, 256, stdin);
when I run the program, it runs this line and then just stopped because of a segmentation fault. The silly printfs are just for me checking where it stopped exactly.
And one more thing, it doesnt always has segmentation faults there, sometimes it works, but sometimes it doesnt. Please help Ive been wrecking my head for days about this.
The input function call is this line
addContacts(&firstPtr, &lastPtr);
firstPtr and lastPtr are pointers, aimed to be the pointer to the beginning and end of the linked list
/* This Function assumed that the input given is already correct, there are no exception handling
* addContact : gets data from the user about a record(i.e. name, address, etc)
* Input: pointer to pointer (first and last of the dynamic linked list)
* Output : Add contact(s) to the list
*/
void addContacts(contact **firstPtr, contact **lastPtr)
{
int i = 0;
char temp[257]; //input buffer
char *ptr = NULL; //var to hold strndup
int input = 0;
contact *inputPtr;
contact *loopPtr;
contact *prevPtr;
do
{
inputPtr = (contact *) malloc(sizeof(contact));
if(inputPtr == NULL)
{
printf("Memory Full!\n");
return;
}
printf("Adding New Contact:\n");
printf("First Name:\t");
fgets(temp, 256, stdin);
WordCap(temp);
ptr = strndup(temp, lastAlphaNumPos(temp));
strcpy(inputPtr->fn, ptr);
free(ptr);
printf("Last Name:\t");
fgets(temp, 256, stdin);
WordCap(temp);
ptr = strndup(temp, lastAlphaNumPos(temp));
strcpy(inputPtr->ln, ptr);
free(ptr);
printf("Address:\t");
fgets(temp, 256, stdin);
WordCap(temp);
ptr = strndup(temp, lastAlphaNumPos(temp));
strcpy(inputPtr->ad, ptr);
free(ptr);
printf("Postal Code:\t");
do
{
fgets(temp, 256, stdin);
ptr = strndup(temp, 6);
strcpy(inputPtr->pc, ptr);
free(ptr);
}while(!postalCheck(inputPtr->pc));
printf("Phone Number: \t");
do
{
printf("z");
fgets(temp, 256, stdin); printf("a");
ptr = strndup(temp, 10); printf("b");
strcpy(inputPtr->pn, ptr); printf("c");
free(ptr); printf("d");
}while(!isValidPhoneNumber(inputPtr->pn));
printf("-2");
inputPtr->nextPtr = NULL;
printf("-1");
//if the input is the first ever element of the list
if(*firstPtr == NULL && *lastPtr == NULL)
{
*firstPtr = inputPtr;
*lastPtr = *firstPtr;
printf("add another record?");
input = getYesNo();
if(input == 1) continue;
else break;
}
printf("0");
//Start insertion sort
loopPtr = *firstPtr;
prevPtr = NULL;
printf("1");
while(strcmp(inputPtr->ln, loopPtr->ln) > 0)
{
prevPtr = loopPtr;
loopPtr = loopPtr->nextPtr;
} printf("2");
if(prevPtr != NULL)
{
prevPtr->nextPtr = inputPtr;
inputPtr->nextPtr = loopPtr;
}
else
{
inputPtr->nextPtr = *firstPtr;
*firstPtr = inputPtr;
} printf("3");
while((*lastPtr)->nextPtr != NULL)
{
*lastPtr = (*lastPtr)->nextPtr;
}
printf("4");
printf("add another record?");
input = getYesNo();
}while(input == 1); //if the input is 1, keep looping
printf("\n");
}