Faust
Faust

Reputation: 99

What is the difference between pointers and pointers with allocated memory?

sstruct *temp1;
sstruct *p;
sstruct *temp2=new sstruct;

If I try to do something like this

temp1=p;
temp2=p;

is there any diffrence?

Upvotes: 1

Views: 94

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145289

The pointer p is not explicitly initialized. So if this is a local variable it has an indeterminate value. If, OTOH., it's in namespace scope, then it's zero-initialized.

Assuming that it's an indeterminate value the subsequent assignment temp1=p has Undefined Behavior. Anything might happen. These things that can happen include (1) nothing, and (2) a crash.

If nothing happens, then the second assignment, temp2=p, loses the original value of temp2, which was the pointer to a dynamically allocated object. So this then is a memory leak. On top of the Undefined Behavior.


In original Pascal pointers always pointed to dynamically allocated objects. There was no way to take the address of a variable. This was a somewhat higher level view of pointers, and the Pascal pointers were single object pointers, not pointers to arrays.

In original C, which C++ was based on, pointers were more like low level memory addresses. A C or C++ pointer value can be obtained by using the address operator, &, on some object. Or you can get a pointer as an implicit conversion of an expression referring to an array (you then get a pointer to the array's first item).


There are three main notations for denoting a nullvalue of pointer type.

int* p = 0;              // Core language, original C.
int* p = nullptr;        // Core language, C++11 and later.
int* p = NULL;           // Library, `<stddef.h>`.

I recommend using the newer nullptr notation.

It's more readable and it fares better when used with so called perfect forwarding (whose main imperfection is that it doesn't deal correctly with 0, forwarding it as an int value).

Upvotes: 1

krzaq
krzaq

Reputation: 16431

First of all, since p is uninitialized you invoke undefined behavior by reading from it (if the code is in function scope). But for the following code

sstruct *temp1;
sstruct *p = nullptr;
sstruct *temp2=new sstruct;

temp1=p;
temp2=p;

both assignments are no different (sans the destination). temp1 and temp2 are left with nullptr value and the struct you previously allocated for temp2 has been leaked.

Upvotes: 1

Related Questions