Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a static pointer in C++

I have a class with a static member that's a pointer like so :

animation.h

class Animation
{
public:
    Animation();
    static QString *m;

};

animation.cpp

#include "animation.h"

QString* Animation::m = 0;

Animation::Animation()
{
}

When I try to initialize that 'm' pointer from another class like so :

Animation::m = new QString("testing");

It works.

But when I do it this way :

QString x("Testing");
Animation::m = &x;

The program crashes.

What is wrong with this second method ?

Also I would like to have that static pointer as private so I can make static getter and setter functions to it. The setter should use the second method as the 'x' will come in a parameter so I'm stuck.

Thanks for any help!

like image 639
Yassir Ennazk Avatar asked May 16 '12 14:05

Yassir Ennazk


People also ask

How to initialize pointer variable in C++?

There are two ways to initialize a pointer variable. You can use reference operator & to get memory location of a variable or you can also directly assign one pointer variable to other pointer variable. Examples to initialize pointer variable

What is the use of static pointers in C++?

A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication. Extern storage class specifies that the variable is defined elsewhere in a large program.

What is static and extern in C programming?

Static and extern are storage classes in C which defines scope and life-time of a variable. Similar to any variables in C, we can use these keywords with pointers for different use cases.

Is the address of a static pointer constant throughout the execution?

Address of static pointer is constant throughout the execution of program. But where it points-to can be modified. A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.


1 Answers

I bet it's not crashing on that line, but afterwards.

The problem is that you're taking the address of a variable located in automatic memory, and probably try to access it afterwards. The variable x will be destroyed when it's scope ends, but Animation::m will still point to that memory (memory you no longer own after x went out of scope). This results in undefined behavior.

Just like the following would be illegal:

int* x = NULL;
{
   int k = 3;
   x = &k;
}
*x = 4;

Workaround assign to the value, not the pointer (provided it was previously assigned to a valid QString*):

QString x("Testing");
*(Animation::m) = x;
like image 116
Luchian Grigore Avatar answered Oct 10 '22 16:10

Luchian Grigore