Linked list

  • Thread starter Alexander Hunziker
  • Start date
A

Alexander Hunziker

Hello everybody,

I'm trying to program a linked list, but unfortunately it segfaults when
I run the program. The code is basically the same as one can find in
several places in the internet. With gdb I found out, that my root->next
points to some strange memory area instead of where it should.

The program segfaults in the while loop in list_append during the third
call of list_append.

Can somebody help me? I'll also gladly send the whole code and Makefile
to somebody personally if he/she's willing to look at it.

Thanks,
Alex

Here's my code:

===== stl.h =====

typedef struct {
float x, y, z;
} point;

typedef struct {
point n;
point v1;
point v2;
point v3;
} triangle;

typedef struct node *nodeptr;

typedef struct node{
triangle tri;
nodeptr next; //Zeiger auf einen Listenknoten
} node;

void list_append(nodeptr node);




===== list.c =====

#include "stl.h"

nodeptr root = NULL;

void list_append(nodeptr node)
{
nodeptr cur_node;

if(root == NULL){
root = node;
root->next= NULL;
} else {
cur_node = root;
while (cur_node->next != NULL)
cur_node = cur_node->next;
cur_node->next = node;
cur_node = cur_node->next;
cur_node->next = NULL;
}
}



===== main.c =====

nodeptr cur_triangle

for(i = 1; i < number_of_triangles; i++)
{
// Values are being read into temptriangle array
cur_triangle = (nodeptr) malloc(sizeof(nodeptr));
cur_triangle->tri.n.x = temptriangle[0];
cur_triangle->tri.n.y = temptriangle[1];
cur_triangle->tri.n.z = temptriangle[2];
cur_triangle->tri.v1.x = temptriangle[3];
cur_triangle->tri.v1.y = temptriangle[4];
cur_triangle->tri.v1.z = temptriangle[5];
cur_triangle->tri.v2.x = temptriangle[6];
cur_triangle->tri.v2.y = temptriangle[7];
cur_triangle->tri.v2.z = temptriangle[8];
cur_triangle->tri.v3.x = temptriangle[9];
cur_triangle->tri.v3.y = temptriangle[10];
cur_triangle->tri.v3.z = temptriangle[11];

list_append(cur_triangle);
}
 
K

Keith Thompson

BGreene said:
Has nothing to do with C
[...]

First, please don't top-post.

Second, what makes you think the question has nothing to do with C?

Third, we answered the OP's question several days ago (the problem was
an incorrect argument to malloc()).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top