-
Segmentation Fault
Hi All.
I am a Student of Computer Science. I have just started programming in C++.
I was running this program which compiled and run successfully on Windows machine. But when I run it on Linux machine it compiled successfully but on running it gives SEGMENTATION FAULT. This is program....
Code:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class first{
public:
int a;
};
class second{
public:
void show(int x);
first *p;
};
void second::show(int x){
p->a=x;
cout<<(p->a);
}
void main(){
second s, *t;
clrscr();
t=&s;
t->show(2);
getch();
}
Please help.
Thanks in Advance.
--Ajay
-
Firstly, that code shouldn't compile on a linux machine because linux compilers don't support conio.h. Secondly, the segmentation fault comes from the fact that you never point p to anywhere. This'll work better:
Code:
#include<iostream>
#include<stdio.h>
using namespace std;
class first{
public:
int a;
};
class second{
public:
second() { p = new first; }
~second() { delete p; }
void show(int x);
first *p;
};
void second::show(int x){
p->a=x;
cout<<(p->a);
}
void main(){
second s, *t;
t=&s;
t->show(2);
}
-
-
The problem is that you have a pointer variable p inside class second, but you never initialize that variable so it doesn't point at anything. When you try to use it anything can happen. It might appear to work, or it might crash, or it might give strange values. That is called undefined behavior. The fact that it worked on Windows and not on Linux is just coincidence.
So you need to initialize the pointer to something. One way is to use dynamic allocation like Noir did.