Tebe
Tebe

Reputation: 3214

c++ trying to fail constructor

I'm trying to get segment fault, but I can't get it and I wonder why.

#include <iostream>
using namespace   std;


class A{

 public:
  char *field_;

   A(char *field):field_(field) {
   // I believe(suppose) that it's equal to
   // field_ = field;
   // so actual initial string wasn't copied, only a pointer to it
   }
 void show() {
    cout<<field_<<"\n";
}
};

int main(){

   A *obj;

{
    char *line="I should be freed";
    obj = new (nothrow) A(line);
}

  // After exiting from the previous scope,
  //  char *line variable should be freed. 
  // Constructor of class A didn't make byte for byte 
  //copying, so we cannot have
  // access to it for sure 

for(int i=0;i<4;i++)  // trying to clear stack and erase char *line  variable
 char something[10000];

obj->show(); // and it works correctly!!!! why?


 delete obj;
 return 0;
 }

Ok, as I understand it works correctly only because that string wasn't freed from memory. I.e. we are just lucky. And here we have undefined behaviour. Am I right?

Thank you in advance!!

Upvotes: 1

Views: 86

Answers (2)

user405725
user405725

Reputation:

You won't get a segmentation fault because there are no invalid memory references made by your program. I'd guess you think that ""I should be freed" is created on stack and then destroyed or freed somehow, and that is a wrong assumption because that is a constant string literal and it is placed into program data segment and is "alive" for the life of your program.

And even if it was allocated dynamically and freed automatically upon leaving the scope, you still cannot expect your program to receive SIGSEGV in that case. Because undefined behavior does not always result in segmentation faults.

Also, try to never write char *data = "blah-blah";. String literals are assumed to always be constant and trying to modify them is undefined behavior. Though people still hack around this sometimes.

Upvotes: 4

Mahesh
Mahesh

Reputation: 34625

 char *line = "I should be freed";

You still see the content because the string literals has static storage duration. Here the string literal I should be freed resides in read only location and is freed once the program execution completes.

The program has no undefined behavior.

Upvotes: 2

Related Questions