Deleting a Pointer to an array.

Hi all!

I've probably got a dumb question, but I can't seem to find any direct refrences to my subject when I search for it.

I'm trying to figure out how to delete a pointer to an array.

Let me show my code:

1
2
3
4
5
6
7
8
9
10
11
12
	int *p;
	int a[10];
	
	p=a;
	for (int i = 0; i<10; i++)
		p[i]= i;
	
	for (int i = 0; i<10; i++)
		cout << "a[" << i << "]= " << a[i] << endl;
		
	delete []p;	// Produces Segmentation Fault
	delete p;	// Produces Segmentation Fault 


I'm sure that it must be simple, but I'm just not getting it.

Any help will be appreciated!

Thanks!

- James
You can't call delete on a stack allocated object. delete is to be used on objects allocated with new. Notice that delete doesn't delete the pointer, but the object it points to. Example:

1
2
3
int* a = new int[10];
delete[] a;
a = NULL; // a still exists, but it's a dangling pointer now, so we set it to NULL (or 0) 
Oh.

Ok, thanks!

I knew it was a simple answer.

So there is no way to free up the memory taken up by the pointer itself?
Last edited on
The pointer is an automatic object and will be destroyed at the end of the current block, like all other stack objects.
Ok.

Thanks Athar!
Topic archived. No new replies allowed.