I'm using cygwin, installed gcc-g++ to compile c written using notepad++.
I want to create a linked list to store data, but it always reports "Segmentation fault (core dumped)"
I figured out that if I put "printf("OK")" after the "scanf" in the 4th row of the main function it doesn't work but shows Segmentation fault again.
Is this a memory management problem? or Pointer abuse?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node{
int data;
struct Node *link;
}node;
typedef struct Node *nodePointer;
nodePointer GetNewNode(){ // create a new node
nodePointer NewNode;
NewNode = (nodePointer) malloc(sizeof(node));
if (NewNode == NULL)
printf("memery is not enough");
return NewNode;
}
nodePointer insert(nodePointer ptr,nodePointer L,int NewData){
nodePointer NewNode,trace;
NewNode = GetNewNode();
if(ptr==NULL){ //to insert first Node
ptr->link = NewNode;
NewNode->link = NULL;
NewNode->data = NewData;
L = ptr;
}
else{ //after insert first Node,insert next Node
trace = L;
while(trace->link!=NULL) trace = trace->link;
trace->link = NewNode;
NewNode->data = NewData;
}
return L;
}
int main(){
int data;
nodePointer ptr=NULL,L=NULL,visit=NULL;
printf("input data to storage, input 0 to print data\n");
scanf("%d",&data);
while(data!=0){ // input data to store, input 0 to print data
L = insert(ptr,L,data);
scanf("%d",&data);
}
visit = L;
while(visit->link!=NULL)
printf("%d",visit->data);
}
typedef struct Node *nodePointer;Never hide pointers behind typedefs, that's bad style as it makes the program harder to read and understand. - Lundin... = malloc(sizeof(node));works by coincidence (unless the OP uses a C++ compiler, which he should not) - wildplassergccto compile C , andg++to compile C++. They are different languages. - M.M