0

Say I have

#include<iostream.h>

int tempNum;

struct node {
        int data;
        struct node *next;
};
struct node *newNode = NULL;

int main(void) {
        tempNum = 5;
        newNode->data = tempNum; //gives seg fault
}

*edit - I'm trying to add tempNum to the very first node.

I haven't worked with linked lists in a while and it's really giving me a headache. What's wrong?

3
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Aia
0

A nice link for linked lists: click

a few things:
- Why is tempnum a global variable?
- iostream.h is outdated, use <iostream> instead.
- you probably want to post this is the C++ forum
- main always return something (an int)

The reason why the program crashes is this line:

struct node *newNode = NULL;

You make a pointer to a node struct and then point it to nothing (NULL). ==> Seg fault

Niek

0

I was going nuts when I wrote this, it's supposed to be #include<stdio.h>, very sorry.

*edit - So do I just need to allocate a memory location to newNode? If so how?

0

*edit - So do I just need to allocate a memory location to newNode? If so how?

Using malloc defined in stdlib.h

*newNode = malloc ( sizeof ( struct node ) );

Any dynamic memory you allocate, it needs to be freed at some point, when you're done; using the function free().

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.