0

I have below code and It gives an error as "segmentation fault" in some compiler but for other compilers it gives "40" as output. Why is there difference?

#include <stdio.h>

class A{
    int *ptr;
    public:
    void set(int val) const;
};
void A::set(int val) const{
    *ptr = val;
    printf("%d", *ptr);
}

int main(){
    A a;
    a.set(40);
    return 0;
}
Selcuk
  • 109
  • 2
  • 11

1 Answers1

3

ptr is an uninitialized pointer. When you deference an unitialized pointer, it's undefined behaviour, anything can happen.

You should initialize ptr in the constructor

class A{
    int *ptr;
    public:
    A();
    void set(int val) const;
    
};

A:A()
{
    ptr = new int();
} 


A:~A()
{
   delete ptr;
}
user93353
  • 13,733
  • 8
  • 60
  • 122