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.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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);
}
}

Recommended Answers

All 2 Replies

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.

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.