user2994219
user2994219

Reputation: 115

segmentation fault happened in some compiler but not others

I have the following code. The compiler g++ in ubuntu12.04 tell me there is segmentation fault. But when I tried the same code in MingW g++ complier, it passes.

Any ideas?

#include<iostream>
using namespace std;

class ListNode{
    public:
        ListNode *next;
        int val;
        ListNode(int x):val(x),next(NULL){};
    };

    int main(){
        ListNode *head;
        head->val=0;
        ListNode *p=head;


        for(int i=1;i<=10;i++){
            p->next=new ListNode(i);
            p=p->next;
        }
    return 0;
}

Upvotes: 0

Views: 130

Answers (3)

user1810087
user1810087

Reputation: 5334

You are using head before allocating it. This is undefined behaviour. On the MinGW system it is pure "luck" that it isn't crashing, but it still invalid. You have to allocate head first:

ListNode *head;
head = new ListNode(0);

// do some stuff

// delete head;

Upvotes: 2

MikeMB
MikeMB

Reputation: 21136

The line

head->val=0;

accesses a member variable val of an object head is supposed to point to, but head doesn't point to any object, yet.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

this code

ListNode *head;
    head->val=0;

is invalid. You did not allocate memory fot ListNode. So you can not write head->val=0;

Upvotes: 0

Related Questions