0

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);
}
}

Edited by happygeek: fixed formatting

3
Contributors
2
Replies
3
Views
11 Years
Discussion Span
Last Post by Narue
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.

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.