• Advertisement
Sign in to follow this  

dynamically deleting arrays

This topic is 4929 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
> p = "hello";
You have a mem leak here because you are assigning new address here to p pointer. You must first free array memory.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement