Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Logical issue?

Vin ParVin Par Member Posts: 1

Hello,

I am trying to implement a basic Linked List in C. As part of the implementation, I have written a function create_list(). The source code for this function is as follows:

`

typedef struct node{
char* data;
struct node* next;
}node;

node* create_list(char* pChar, node* pN)
{
short count = 0, index = 0;
assert(NULLINT != (count = strlen(pChar)));
node* pHead = NULL;
node* pTail = NULL;

do
{
if(NULLINT == index)
{
pN = malloc(sizeof(node));
assert(NULL != pN);
pN->data = malloc(sizeof(char));
assert(NULL != pN->data);
*pN->data = pChar[index++];
pN->next = NULL;
pHead = pN;
pTail = pN->next;
}
else
{
pTail = malloc(sizeof(node));
assert(NULL != pTail);
pTail->data = malloc(sizeof(char));
assert(NULL != pTail->data);
*pTail->data = pChar[index++];
pTail->next = NULL;
pN = pTail;
pTail = pTail->next;
}

}while(count--);

return pHead;
}

From main(), the routine create_list() is invoked as follows:

int main()
{

char name[BUFFER] = {'v', 'i', 'n', 'o', 'd', NULLCHAR};
node* pN = NULL;

pN = create_list(name, pN);
print_list(pN);
delete_list(pN);

return 0;
}

The print_list() routine just prints all the list elements:

void print_list(node* pN)
{
assert(NULL != pN);
do
{
fprintf(stdout,"%c\n", *(pN->data));
pN = pN->next;
}while(pN != NULL || pN->next != NULL);

return;
}

The problem I see during runtime is that only the head node gets printed ('v' in the above code), after which there occurs a segmentation fault in print_list() because the next element of the head node is NULL.

Could anyone point out the issue with the logic adopted inside create_list() which results in this error?
`

Sign In or Register to comment.