Regarding Dynamic Memory Allocation

S

saurabh29789

Is it safe to move(increment/decrement/re-position) the pointer to
whom the dynamic memory was allocated to??

I mean :

{

int *p, *q;

p = (int*)malloc(10*sizeof(int));

q=p;
p = p+5;
..
..
Some Code
..
..
p = q;

free(p);
}

In this code, will the memory be safely freed ?

Some one told me that if I move the pointer to point to some other
(valid) location and then even if I return it back to the previous
location (starting address of the dynamically allocated memory), then
it might lose some information that it stores after the dynamic
allocation is done and, thus, the memory blocks might not be freed.

Is it so?
 
J

jameskuyper

saurabh29789 said:
Is it safe to move(increment/decrement/re-position) the pointer to
whom the dynamic memory was allocated to??

Yes, but you have to either save (which is the simplest approach) or
recreate (which is much trickier) the original pointer value before
passing it to free().
I mean :

{

int *p, *q;

p = (int*)malloc(10*sizeof(int));

q=p;
p = p+5;
.
.
Some Code
.
.

You could, at this point, call free(p-5), though I would not recommend
it.
p = q;

free(p);

That works, though free(q) is equally good.
}

In this code, will the memory be safely freed ?
Yes.

Some one told me that if I move the pointer to point to some other
(valid) location and then even if I return it back to the previous
location (starting address of the dynamically allocated memory), then
it might lose some information that it stores after the dynamic
allocation is done and, thus, the memory blocks might not be freed.

Is it so?

No.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top