the second printf, identical to my first printf, makes the program crash - c

i'm obviously not blaming printf here, i probably messed up my mem allocations and access but i can't understand where i did wrong. the program crash on the second printf in main. It also crash on the third if i comment the second one. Actually it crash whenever i access p after the first printf !
Can someone explains me what i am doing wrong ?
Thanks a lot.
typedef struct
{
char * firstname;
char * lastname;
int age;
} person;
person * new_person(char * firstname, char * lastname, int age)
{
person p;
int lf = strlen(firstname);
int ll = strlen(lastname);
p.firstname = (char *)malloc(++lf * sizeof(char));
p.lastname = (char *)malloc(++ll * sizeof(char));
strcpy(p.firstname, firstname);
strcpy(p.lastname, lastname);
p.age = age;
return &p;
}
int main()
{
person * p = new_person("firstname", "last", 28);
printf("nom : %s ; prenom : %s ; age : %d\n", p->lastname, p->firstname, p->age);
printf("nom : %s ; prenom : %s ; age : %d\n", p->lastname, p->firstname, p->age);
printf("nom : %s ; prenom : %s ; age : %d\n", (*p).lastname, (*p).firstname,(*p).age);
return 0;
}

You're returning the address of a local variable.
You can either modify your new_person to take an argument (a pointer to a person) or you can malloc one inside the function and manipulate that.
The person you declared in your function goes out of scope when the function returns. Everything that happens to it after that is undefined. It might coincidentally keep its value for a while, but you should not depend on this. When you make your call to printf, the stack grows and overwrites the old location of your person with new stuff.

I think the issue is in this line:
return &p;
Notice that you are returning a pointer to a local variable. This results in undefined behavior, since as soon as the function returns, the local variable p no longer exists. As a result, reading or writing that pointer will read or write garbage data.
The fact that this doesn't immediately crash is an artifact of how the compiler generates code. Chances are, the first time you call printf, it reuses space that was previously used for p in a way that, by sheer coincidence, works out fine. However, after the function returns, its stack frame has clobbered the old memory for p. As a result, the second call to printf is reading garbage data left behind from the call to printf, hence the crash.
(Specifically: when you pass the parameters, it copies the pointers to the strings onto the stack, so when printf runs, it's probably trashing the original pointers, but using the copies. The second call then loads garbage pointers from the expired printf stack frame, since it lives at the same address that p used to live in.)
To fix this, consider changing p to a pointer to a person and then using malloc to allocate it. That way, the memory persists beyond the function call, so this crash should go away.
Hope this helps!

person p;
// stuff
return &p
This is wrong. After the function returns, the local variable is leaving the scope - its address will be invalid. You have to allocate the structure on the heap:
person *new_person(char *firstname, char *lastname, int age)
{
person *p = malloc(sizeof(*p));
p->firstname = strdup(firstname);
p->lastname = strdup(lastname);
p->age = age;
return p;
}

The problem is in the function new_person. You create person p on the stack and return its address. You need to allocate person* p = new person(.....

Related

Problems with array of pointers to struct

After defining the type student (which is a struct made of two arrays of characters and an int), I've created an array of pointers to student, which I need in order to modify its content inside of a series of functions.
int main(void)
{
student* students[NUMBER_OF_STUDENTS];
strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
return EXIT_SUCCESS;
}
My problem is that this simple piece of code returns -1 as exit status after running. Why is that?
The pointer students[0] is uninitialized. Dereferencing it results in undefined behavior.
Initialize it with the address of a valid object before attempting to access it.
student test;
students[0] = &test;
strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
Because it is UB. You have only pointer without the actual structs allocated.
students[x] = malloc(sizeof(*students[0]));
or statically
student s;
students[x] = &s;
or
students[x] = &(student){.name = "test", .surname ="test", .grade = 18};
The pointers are pointing to nowhere since you have not allocated any memory for them to point to.
int main(void)
{
student* students = (student*)malloc(sizeof(student)*[NUMBER_OF_STUDENTS]); \\malloc dynamically allocate heap memory during runtime
strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;
return EXIT_SUCCESS;
}
*Note Edit by marko -- Strictly the pointers are pointing to whatever was last in the stack location or register holding it - it may be nothing, or something you actually care about. The joys of UB

Members of struct are being modified, but why? [duplicate]

This question already has answers here:
error: function returns address of local variable
(8 answers)
Closed 4 years ago.
I've been trying to write a program to solve a problem (ex. 19, Chapter 10 'C How to Program' 8th Ed, Deitel & Deitel), but I'm having a lot of trouble trying to identify the source of an issue I'm having.
I've been trying to pass some data to a function 'setData', which assigns the various values passed in to the members of a structure 'HealthProfile'. This seems to be happening successfully, and the function returns a pointer to a struct object to main. The pointer is then passed to function 'printStruct', and this is where the problem occurs. Each time the pointer is passed to the function, the function seems to be altering the values stored in each of the structure members, but I don't know why. I'm not trying to alter the member values, the point of passing the pointer to the structure to each function is so that the functions have access to the values contained in the members (my actual program has other functions, but I haven't included them because I'm still working on them, plus the issue I'm having is illustrated by function 'printStruct' alone.
Can anyone tell me where I've gone wrong?
I have tried a lot of different things, but nothing seems to work. I suspect that maybe the solution to the problem is that I should be passing a pointer to a pointer to the functions instead of a pointer, but I haven't had any luck in trying to fix the program this way. I also thought maybe I should be declaring the structure members as constant, but again no luck.
I've included a few printf statments in main to illustrate that the value of the pointer hasn't changed, but the value of the members of the structure have after the first call of function 'printStruct' (if printStruct is called a second time, a segmentation fault occurs).
#include <stdio.h>
typedef struct {
char *firstName;
char *lastName;
char *gender;
int birthDay, birthMonth, birthYear;
double height, weight;
} HealthProfile;
HealthProfile * setData(char first[20], char last[20], char gender[2],
int BirthDay, int BirthMonth, int BirthYear,
double Height, double Weight);
void printStruct(HealthProfile * variablePtr);
int main(void)
{
char FirstName[20], LastName[20], Gender[2];
int age, BirthDay, BirthMonth, BirthYear, maxRate = 0, targetRate = 0;
double bmi, Height, Weight;
HealthProfile *variablePtr;
puts("\n** Health Profile Creation Program **");
printf("\n%s\n\n%s", "Enter First Name", "> ");
scanf("%s", FirstName);
printf("\n%s\n\n%s", "Enter Last Name", "> ");
scanf("%s", LastName);
printf("\n%s\n\n%s", "Enter Gender (M/F)", "> ");
scanf("%s", Gender);
printf("\n%s\n\n%s", "Enter date of birth (dd/mm/yyyy)", "> ");
scanf("%d/%d/%d", &BirthDay, &BirthMonth, &BirthYear);
printf("\n%s\n\n%s", "Enter Height (m)", "> ");
scanf("%lf", &Height);
printf("\n%s\n\n%s", "Enter Weight (kg)", "> ");
scanf("%lf", &Weight);
variablePtr = setData(FirstName, LastName, Gender, BirthDay,
BirthMonth, BirthYear, Height, Weight);
printf("Address pointer: %p\n", variablePtr);
printf("Address pointer (deref): %p\n", variablePtr->firstName);
printf("Address pointer (deref): %p\n", variablePtr->lastName);
printStruct(variablePtr);
printf("Address pointer (deref): %p\n", variablePtr->firstName);
printf("Address pointer (deref): %p\n", variablePtr->lastName);
/* printStruct(variablePtr); */
}
HealthProfile * setData(char first[20], char last[20], char gender[2],
int BirthDay, int BirthMonth, int BirthYear,
double Height, double Weight)
{
HealthProfile profile, *profilePtr;
profilePtr = &profile;
profile.firstName = first;
profile.lastName = last;
profile.gender = gender;
profile.birthDay = BirthDay;
profile.birthMonth = BirthMonth;
profile.birthYear = BirthYear;
profile.height = Height;
profile.weight = Weight;
return profilePtr;
}
void printStruct(HealthProfile * variablePtr)
{
printf("\n%s%s\n%s%s\n%s%s\n%s%d/%d/%d\n%s%.2lfm\n%s%.1lfkg\n",
"First Name: ", variablePtr->firstName,
"Last Name: ", variablePtr->lastName,
"Gender: ", variablePtr->gender,
"DOB: ", variablePtr->birthDay, variablePtr->birthMonth,
variablePtr->birthYear,
"Height: ", variablePtr->height,
"Weight: ", variablePtr->weight);
}
Based on the way I've written the code, I was expecting the structure pointer passed to 'printStruct' not to be changed after the member values are printed. I would think I could call the function multiple times with no alteration to member values, but after just one call things are changed.
The Problem here is, that your pointer points to an address on the stack, which means, it's 'lifetime' or scope ends, when the Function setData returns. The next calls' stackframe overwirtes in part or whole the place in memory where your pointer points to. This leads to random and sometimes possibly correct output.
To solve this either allocate memory in the heap, instead of pointing to the address of a local variable ( malloc ) or declare a local variable im Main() and pass a pointer to setData.
Both solutions will prevent the issue you Are having.
Your problem is the time local variables are valid:
Both function arguments and local variables are only present in memory as long as the corresponding function is being executed. When the function has finished, the variables become invalid and may be overwritten with other data.
Now let's look at the following part of your code:
... setData( ... )
{
HealthProfile profile, *profilePtr;
profilePtr = &profile;
...
return profilePtr;
}
profilePtr contains a pointer to the local variable profile. As soon as the function setData has finished, this variable is no longer valid and may be overwritten.
The pointer profilePtr (returned by the function) will point to the memory where the variable profilePtr was located before. In other words: The value of the pointer profilePtr also becomes invalid because it points to a variable which no longer exists.
Maybe you have luck and the memory is not needed and the variable is not overwritten. But with a certain probability the function printf will need that memory and overwrite that (no longer valid) variable.
You might try this:
variablePtr = setData( ... );
printf("BirthDay (first time): %d\n", variablePtr->BirthDay);
printf("BirthDay (second time): %d\n", variablePtr->BirthDay);
With a high probability the following will happen:
printf will need the memory occupied by profile and therefore overwrite the data. However, in both lines above the value of BirthDay will first be read from the structure before the function printf is actually called.
Therefore the first printf will print the correct value of BirthDay while the second printf will print a wrong value.

C Pointer Referencing

I have the following code which simply prints out an introduction for a person's name.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char* firstname;
char* lastname;
}Person;
void intro(void *person){
printf("The person you are looking for is %s %s\n", ((Person *)person)->firstname, ((Person *)person)->lastname);
}
int main()
{
Person *a = NULL;
a = (Person *)malloc(sizeof(Person));
char *first = NULL, *last = NULL;
first = (char *)malloc(sizeof(char)*20);
strncpy(first,"Bob", 20);
last = (char *)malloc(sizeof(char)*20);
strncpy(last,"Newmonson", 20)
a->firstname = first;
a->lastname = last;
intro(a);
return 0;
}
Produces the output
The person you are looking for is Bob Newmonson
However changing intro(a) to intro(&a) produces
The person you are looking for is �# Newmonson
When I open the first attempt in GDB and break on line 10 I find the address of person=0x601010. Both the first name and last name are stored where I would expect, 0x04006b9 and 0x4006bd since they where declared earlier in the stack.
What gets me is when I run GDB with the changes made to intro(&a). The address of person is now 0x7fffffffffdd38, with the first name pointing to 0x601010 and the last name pointing to 0x4006db.
Can anyone help explain to be what is going on and why I can still access the proper address of the last name in the second test.
EDIT :
As everyone seems to keep asking about it the void * was for a threading portion of this code that I did not include.
It's because a is already pointer to a Person structure; therefore intro(&a) passes a pointer to that pointer, but intro() treats it's argument as a pointer to Person.
Also, if intro() is intended to work on a Person, it should declare a Person * argument, not a void *.
The address being held inside of the pointer variable a is not the same as the address of the actual memory location being taken up by a.
And address like 0x601010 is a "low" memory address, and is going to typically be somewhere on the heap. An address like 0x7fffffffffdd38 is a very "high" address, and will typically be on the stack. So &a is giving you the actual address of the variable a on the stack, and it is passing that value to the function, not the value 0x601010 being stored inside the pointer variable a, and representing the first address of the allocated memory buffer returned from malloc.
First of all:
/* allocate space for 20 characters and make 'first' point to that space. */
first = (char *)malloc(sizeof(char)*20);
/* now make 'first' point to the string Bob. Leak the memory that was allocated before. */
first = "Bob";
/* Rinse, lather, repeat. */
last = (char *)malloc(sizeof(char)*20);
last = "Newmonson";
Now to explain why using intro(&a) gives you unexpected results:
intro expects a pointer, which it assumes points to a structure of type Person. You create a pointer to a Person and then allocate space for it.
Calling intro(a) causes the pointer to Person to be passed as a pointer to void to intro, which then treats it as a pointer to Person and all is well.
Calling intro(&a) however takes the address of a and passes that in. Again, intro tries to treat it as a pointer to Person but that won't work because what you've passed is a pointer to a pointer to a Person. You're passing tomatoes to a function that thinks it's getting oranges. Both are fruit, and you will get juice, although you are probably not going to to be very happy when your breakfast is served with delicious tomato juice instead of delicious orange juice.
If you are asking why calling intro(&a) causes the first name to be mangled but the last name to be printed, the answer is because of sheer luck: the string with the last name just happened to be in the right position in memory.
try this:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char* firstname;
char* lastname;
}Person;
void intro(Person *person){
printf("The person you are looking for is %s %s\n", (person)->firstname, (person)->lastname);
}
int main()
{
Person *a = NULL;
char *first = NULL, *last = NULL;
a = (Person *)malloc(sizeof(Person));
first = (char *)malloc(sizeof(char)*20);
first = "Bob";
last = (char *)malloc(sizeof(char)*20);
last = "Newmonson";
a->firstname = first;
a->lastname = last;
intro(a);
return 0;
}
hope it helps...

List to list assignment becomes garbage

I'm having some trouble with the following:
void BuildList(cs460hwp hw)
{
FILE* fp;
fp = fopen("HW2input.dat", "r");
if(fp == NULL)
{
printf("Couldn't open the file.");
return;
}
int numStudents;
int i;
bool success;
char* dueDate = malloc(9*sizeof(char));
char* course = malloc(7*sizeof(char));
char* wsuid = malloc(9*sizeof(char));
char* subDate = malloc(9*sizeof(char));
double points1 = 0;
double points2 = 0;
cs460hwp stuInsert = NULL;
fscanf(fp, "%d", &numStudents);
fscanf(fp, "%s", dueDate);
for(i = 0; i < numStudents; i++)
{
stuInsert = malloc(sizeof(cs460hwp));
fscanf(fp, "%s %s %s %lf", course, wsuid, subDate, &points1);
strcpy(stuInsert->course, course);
strcpy(stuInsert->wsuid, wsuid);
strcpy(stuInsert->subdate, subDate);
stuInsert->points1 = points1;
stuInsert->points2 = CalculatePoints(dueDate, subDate, points1);
stuInsert->nextPtr = NULL;
if(hw == NULL)
{
hw = stuInsert;
}
else
{
stuInsert->nextPtr = hw;
hw = stuInsert;
}
}
free(course);
free(wsuid);
free(subDate);
free(dueDate);
PrintGrades(hw);
fclose(fp);
}
struct hwpoints
{
char course[7];
char wsuid[9];
char subdate[9];
double points1;
double points2;
struct hwpoints *nextPtr;
};
typedef struct hwpoints *cs460hwp;
My goal here is to insert every entry to the top of the list. However, whenever I try to assign anything to nextPtr (such as in the else clause), it gets filled with garbage values. They're mostly truncated versions of old data, which leads me to believe they're being taken from the heap. I've been reading (a lot), but I'm having trouble finding advice on this particular problem.
nextPtr always becomes junk, and nextPtr->nextPtr causes a segfault. For every iteration of the loop. hw remains fine, but its pointer value never gets updated properly.
Even when I've attempted to move the memory allocation for the struct into a function, I've had the same (or similar) issues.
Can anyone point me in the right direction?
Two problems.
1) As pb2q mentioned, you are passing a pointer to a struct and trying to assign what the arg points to. That's allowed by the compiler, but it doesn't do anything for you outside the function. It might be OK in your case if:
void main()
{
cs460hwp hw = NULL;
BuildList(hw);
return;
}
Is the whole of your function. I don't know the assignment so you need to figure out if that's acceptable to you or not.
2) The much bigger problem:
stuInsert = malloc(sizeof(cs460hwp));
Did you check what sizeof(cs460hwp) comes out to be? it's 4. You're allocating enough memory for the size of a pointer, not the size of your structure. I'm pretty sure this is not what you want to do and this is what is killing you. Just for kicks, replace it with malloc(100) and see if your problem goes away. If so you just need to figure out what size you really want. ;)
A problem with your BuildList function is that you're passing a pointer to a struct hwpoints, and you're trying to re-assign what the argument points to. Since function arguments in C are pass-by-value you're only changing the copy of the pointer that your function receives, and those changes won't be reflected in the caller.
You can use this pointer to modify the contents of the list: you can change e.g. hw->course or hw->nextPtr, you can move elements around in your list. But you can't change what the head, hw points to, so you can't insert elements at the beginning of the list.
If you want to change your head pointer, as in these statements:
hw = stuInsert;
// ...
hw = stuInsert;
Then you'll need to pass a pointer to the pointer:
void BuildList(cs460hwp *hw)
And de-reference it as necessary in the body of the function.
I can't be sure that this is the cause of the output that you're observing, which may be due to other problems. But if, after some number of calls to BuildList, beginning with a head pointer equal to NULL, you're trying to print your list assuming that it has valid nodes, you could see garbage data.
Thanks to #Mike's answer, we see also that you're not allocating enough space for your list nodes:
stuInsert = malloc(sizeof(cs460hwp));
Will only allocate enough space for a pointer, since cs460hwp is typedef'd to be a pointer to struct hwpoints. You need to allocate enough space for the structure, not a pointer to it:
stuInsert = malloc(sizeof(struct hwpoints));

Returning local data from functions in C and C++ via pointer

I have argument with my friend. He says that I can return a pointer to local data from a function. This is not what I have learned but I can't find a counterargument for him to prove my knowledge.
Here is illustrated case:
char *name() {
char n[10] = "bodacydo!";
return n;
}
And it's used as:
int main() {
char *n = name();
printf("%s\n", n);
}
He says this is perfectly OK because after a program calls name, it returns a pointer to n, and right after that it just prints it. Nothing else happens in the program meanwhile, because it's single threaded and execution is serial.
I can't find a counter-argument. I would never write code like that, but he's stubborn and says this is completely ok. If I was his boss, I would fire him for being a stubborn idiot, but I can't find a counter argument.
Another example:
int *number() {
int n = 5;
return &n;
}
int main() {
int *a = number();
int b = 9;
int c = *a * b;
printf("%d\n", c);
}
I will send him this link after I get some good answers, so he at least learns something.
Your friend is wrong.
name is returning a pointer to the call stack. Once you invoke printf, there's no telling how that stack will be overwritten before the data at the pointer is accessed. It may work on his compiler and machine, but it won't work on all of them.
Your friend claims that after name returns, "nothing happens except printing it". printf is itself another function call, with who knows how much complexity inside it. A great deal is happening before the data is printed.
Also, code is never finished, it will be amended and added to. Code the "does nothing" now will do something once it's changed, and your closely-reasoned trick will fall apart.
Returning a pointer to local data is a recipe for disaster.
you will get a problem, when you call another function between name() and printf(), which itself uses the stack
char *fun(char *what) {
char res[10];
strncpy(res, what, 9);
return res;
}
main() {
char *r1 = fun("bla");
char *r2 = fun("blubber");
printf("'%s' is bla and '%s' is blubber", r1, r2);
}
As soon as the scope of the function ends i.e after the closing brace } of function, memory allocated(on stack) for all the local variables will be left. So, returning pointer to some memory which is no longer valid invokes undefined behavior.
Also you can say that local variable lifetime is ended when the function finished execution.
Also more details you can read HERE.
My counter-arguments would be:
it's never OK to write code with undefined behavior,
how long before somebody else uses that function in different context,
the language provides facilities to do the same thing legally (and possibly more efficiently)
It's undefined behavior and the value could easily be destroyed before it is actually printed. printf(), which is just a normal function, could use some local variables or call other functions before the string is actually printed. Since these actions use the stack they could easily corrupt the value.
If the code happens to print the correct value depends on the implementation of printf() and how function calls work on the compiler/platform you are using (which parameters/addresses/variables are put where on the stack,...). Even if the code happens to "work" on your machine with certain compiler settings it's far from sure that it will work anywhere else or under slightly different border conditions.
You are correct - n lives on the stack and so could go away as soon as the function returns.
Your friend's code might work only because the memory location that n is pointing to has not been corrupted (yet!).
As the others have already pointed out it is not illegal to do this, but a bad idea because the returned data resides on the non-used part of the stack and may get overridden at any time by other function calls.
Here is a counter-example that crashes on my system if compiled with optimizations turned on:
char * name ()
{
char n[] = "Hello World";
return n;
}
void test (char * arg)
{
// msg and arg will reside roughly at the same memory location.
// so changing msg will change arg as well:
char msg[100];
// this will override whatever arg points to.
strcpy (msg, "Logging: ");
// here we access the overridden data. A bad idea!
strcat (msg, arg);
strcat (msg, "\n");
printf (msg);
}
int main ()
{
char * n = name();
test (n);
return 0;
}
gcc : main.c: In function ‘name’:
main.c:4: warning: function returns address of local variable
Wherever it could been done like that (but it's not sexy code :p) :
char *name()
{
static char n[10] = "bodacydo!";
return n;
}
int main()
{
char *n = name();
printf("%s\n", n);
}
Warning it's not thread safe.
You're right, your friend is wrong. Here's a simple counterexample:
char *n = name();
printf("(%d): %s\n", 1, n);
Returning pointer to local variable is aways wrong, even if it appears to work in some rare situation.
A local (automatic) variable can be allocated either from stack or from registers.
If it is allocated from stack, it will be overwritten as soon as next function call (such as printf) is executed or if an interrupt occurs.
If the variable is allocated from a register, it is not even possible to have a pointer pointing to it.
Even if the application is "single threaded", the interrupts may use the stack. In order to be relatively safe, you should disable the interrupts. But it is not possible to disable the NMI (Non Maskable Interrupt), so you can never be safe.
While it is true that you cannot return pointers to local stack variables declared inside a function, you can however allocate memory inside a function using malloc and then return a pointer to that block. Maybe this is what your friend meant?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* getstr(){
char* ret=malloc(sizeof(char)*15);
strcpy(ret,"Hello World");
return ret;
}
int main(){
char* answer=getstr();
printf("%s\n", answer);
free(answer);
return 0;
}
The way I see it you have three main options because this one is dangerous and utilizes undefined behavior:
replace: char n[10] = "bodacydo!"
with: static char n[10] = "bodacydo!"
This will give undesirable results if you use the same function more than once in row while trying to maintain the values contained therein.
replace:
char n[10] = "bodacydo!"
with:
char *n = new char[10];
*n = "bodacydo!"
With will fix the aforementioned problem, but you will then need to delete the heap memory or start incurring memory leaks.
Or finally:
replace: char n[10] = "bodacydo!";
with: shared_ptr<char> n(new char[10]) = "bodacydo!";
Which relieves you from having to delete the heap memory, but you will then have change the return type and the char *n in main to a shared_prt as well in order to hand off the management of the pointer. If you don't hand it off, the scope of the shared_ptr will end and the value stored in the pointer gets set to NULL.
If we take the code segment u gave....
char *name() {
char n[10] = "bodacydo!";
return n;
}
int main() {
char *n = name();
printf("%s\n", n);
}
Its okay to use that local var in printf() in main 'coz here we are using a string literal which again isn't something local to name().
But now lets look at a slightly different code
class SomeClass {
int *i;
public:
SomeClass() {
i = new int();
*i = 23;
}
~SomeClass() {
delete i;
i = NULL;
}
void print() {
printf("%d", *i);
}
};
SomeClass *name() {
SomeClass s;
return &s;
}
int main() {
SomeClass *n = name();
n->print();
}
In this case when the name() function returns SomeClass destructor would be called and the member var i would have be deallocated and set to NULL.
So when we call print() in main even though since the mem pointed by n isn't overwritten (i am assuming that) the print call will crash when it tried to de-reference a NULL pointer.
So in a way ur code segment will most likely not fail but will most likely fail if the objects deconstructor is doing some resource deinitialization and we are using it afterwards.
Hope it helps

Resources