Here I have a segmentation fault caused by my function insert. It's not like one I've seen before though. Run insert once and it works fine. Run it twice and a segmentation fault occurs before insert even gets a chance to run. Could someone explain this?
Code:
#include <stdio.h>
#include <stdlib.h>
struct listnode {
int num;
struct listnode *nextPtr;
};
typedef struct listnode ListNode;
void insert( ListNode **sPtr, int number );
void display( ListNode **sPtr );
int main()
{
ListNode *ptr = NULL;
insert( &ptr, 2 );
insert( &ptr, 3 );
// insert( &ptr, 111 );
display( &ptr );
return 0;
}
void display( ListNode **sPtr )
{
ListNode *currentPtr = NULL;
currentPtr = *sPtr;
while ( currentPtr != NULL ) {
printf( "%10d", currentPtr->num );
currentPtr = currentPtr->nextPtr;
}
}
void insert( ListNode **sPtr, int number )
{
ListNode *newPtr = NULL;
ListNode *currentPtr = NULL;
ListNode *previousPtr = NULL;
// -------------This Test Statement is Never Reached when there are two inserts --------
printf( "test" );
newPtr = malloc( sizeof( ListNode ) );
newPtr->num = number;
newPtr->nextPtr = *sPtr;
if ( newPtr != NULL ) {
printf( "hello" );
if ( *sPtr == NULL ) {
*sPtr = newPtr;
}
else {
currentPtr = *sPtr;
while ( currentPtr->nextPtr != NULL && currentPtr->num < number ) {
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
}