954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

still available even after freeing dynamic allocated memory

I would like to know whether the dynamic memory pointer is still available even after freeing the allocated memory. If I want to allocate and deallocate so many times within a loop , I receive memory corruption. Pls help me how I should do.If I call "free" more than one time, it reports error because allocated memory is already freed even though there is still available. I don't understand this concept . Pls help me.The program is as follows.

Best Rgds,
perlsu

#include #include #include void main() { int i = 0; unsigned char* temp = NULL; unsigned char st[] = "Hello";

for ( i = 0;i < 10;i++) { temp = (unsigned char*) malloc( strlen(st) ); memcpy( temp, st, strlen(st));

if (temp) free(temp);

if (temp) printf("still available"); else printf("already destroyed"); if (temp) free(temp);

} }

perlsu
Newbie Poster
17 posts since Sep 2005
Reputation Points: 10
Solved Threads: 0
 

when you "free" memory, you are deleting the object which "temp" points to, you are not modifying temp itself. What you are left with is a dangling pointer which points to some undefined part of memory, which could contain absolutely anything. you should assign the value of NULL to "temp" after freeing the memory.

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

>I would like to know whether the dynamic memory pointer is still
>available even after freeing the allocated memory.
No, it's not. When you free memory, you must reassign the pointer to memory that you own before you can dereference it again.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You