dynamically deleting arrays

Started by
5 comments, last by izzo 19 years, 6 months ago
This code gives me a core dump, something is wrong with the way I delete the memory. What am I doing wrong ?

	char *p;
	p = new char [50];
	p = "hello";
	cout << p << endl;   // this successfully outputs word hello

	delete[] p; // when this line is commented, program works but im sure there is a memory leak

edit: Put the code into a codebox
Feel free to email me at NYYanks432@hotmail.com if you have any questions
Advertisement
When you do p = "hello" you're actually changing what p is pointing to. In this example, you're pointing to the string "hello" rather than modifying the memory you allocated. You could try something like: strcpy(p, "hello") instead. That way, you'd be modifying your dynamically-allocated memory rather than making p point to a constant string.
Quote:Original post by GameDev135
This code gives me a core dump, something is wrong with the way I delete the memory. What am I doing wrong ?

*** Source Snippet Removed ***

edit: Put the code into a codebox


p = "hello";

It loses the dynamically allocated memory.
> p = "hello";
You have a mem leak here because you are assigning new address here to p pointer. You must first free array memory.
Use strncpy or, better, std::string
guys, i think he's/she's only just started on pointers :)

i'll try to teach ya about pointers real quick..

when you do this: p = new char[50] you're returned a memory address, eg. 0x01 (just an example, its not really like this). this block of memory is 50 chars long, and p only points to the block, kinda like how a sign points to a town (ie, the sign is not the town!)

when you assign p like how you did, you "moved the sign". eg, when you do this: p = "hello", p now points to a new memory block (the memory block thats storing your string "hello") like 0x05.

the problem is, when you assigned p to "hello" you it no longer points to that originally allocated block (0x01), when you try to delete [] p, you're trying to delete memory that you didn't allocate yourself. you should be deleting 0x01, but p is pointing to 0x05, which isn't yours!

doing this is a no no!

hope that helped dude(or dudette)

-Danu
"I am a donut! Ask not how many tris/batch, but rather how many batches/frame!" -- Matthias Wloka & Richard Huddy, (GDC, DirectX 9 Performance)

http://www.silvermace.com/ -- My personal website
Also when you should be aware that when you assign a string like
p = "hello";
the memory that 'p' is pointing to is read only.

cheers
sam

This topic is closed to new replies.

Advertisement