Dynamic allocation

Hi all.

I have a question about dynamic allocation of pointer.
If I allocate a pointer normally (not dynamically), if the pointer is uninitialized, probably I'll get an error message.

For instance:
1
2
3
  	int* ptr;
	*ptr = 4;
	cout << *ptr << endl;


But! If the allocation is dynamic, I won't get an error.

For instance:
1
2
3
4
	int* ptr = new int;
	*ptr = 4;
	cout << ptr << endl;
	delete ptr;


Or even:
1
2
3
4
	int* ptr = new int;
	ptr[4] = 20;
	cout << ptr[4] << endl;
	delete ptr;


The question is - Why...?

Thanks!
A pointer is a variable which contains a number.
That number represents a memory address.

You can print the pointer to see what memory address it contains:

1
2
3
4
5
6
7
std::cout << ptr << '\n';

const char *s = "Hello, World!";

// a cast is required for char pointers, because they're
// treated differently than regular pointers
std::cout << reinterpret_cast<const void *> (s) << std::endl;


When the pointer is not initialized, it contains a garbage value.
The garbage value is not a valid memory address.

Possibly, if you compile in Debug mode (or without Optimizations) the pointer will be initialized to 0.
A pointer pointing to memory address 0 is called NULL (or nullptr in C++11).
And this is also an invalid memory address.

What does the new operator do?
It allocates a chunk of memory then returns the address to it.
So your pointer will contain a valid memory address, and you can read/write to that chunk of memory.

Your first snippet is incorrect because you don't initialize the pointer, and a garbage value cannot be used safely, while a value of 0 cannot be used at all.

Your second snippet is correct.

Your third snippet is incorrect. You must use operator new[] and operator delete[] for dynamic arrays. Otherwise even if the code appears to work, it may crash randomly. In your snippet, you do not own the memory at which ptr[4] is located.

1
2
3
4
5
int *ptr = new int[5]; // available: ptr[0], ptr[1], ptr[2], ptr[3], ptr[4]

ptr[4] = 20;
std::cout << ptr[4] << std::endl;
delete[] ptr;


Edit: lots of mistakes and typos.
Last edited on
consider this:
1
2
3
int a;
int* b; 
b = &a;


b points to the integer at a. It doesn't need it's own memory allocated so we won't bother allocating memory to b unless we really need to.

Now consider:
1
2
3
int a;
int* b = new int;
b = &a;


b pointed to its own integer. But then we set it to point to a. If we wrote anything into the original memory, it's still there but we've lost the address of it and won't be able to find it again. This is a memory leak.
Thanks!
Topic archived. No new replies allowed.