364,036 Members | 5222 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

Is pointer malloc'ed?

Khookie
P: n/a
Khookie
Hi all

I was wondering whether there was a way to know whether a pointer (in
my case, I'm using a char pointer) has been allocated memory through
malloc or not, thus needing to be freed at a later stage?

BTW, I thought this would be a common question - so either I'm just
plain ignorant (coming from a C# and Python background) or my google
skills need to improve.

Oh, and Happy new year everyone!

Chris
Jan 1 '08 #1
Share this Question
Share on Google+
2 Replies


Richard Heathfield
P: n/a
Richard Heathfield
Khookie said:
Hi all
>
I was wondering whether there was a way to know whether a pointer (in
my case, I'm using a char pointer) has been allocated memory through
malloc or not, thus needing to be freed at a later stage?
Um, yeah, kinda. Ish. Well, no. But yes.

My! Wasn't that helpful! :-)

C doesn't support you in your bid to know this, but it doesn't forbid you
from knowing, either. When you allocate memory via malloc, calloc, or
realloc, you know that you are doing so (*but* see below). It is perfectly
possible to store a copy of the pointer thus obtained in some kind of
searchable list, for later lookup.

It is, however, a messy way to deal with memory deallocation, and you have
to remember to remove the copy from the lookup table when you free the
memory.

Also, if you call third-party libraries that allocate memory, well, they
won't know about your super new list, and so they won't know to update it
with the memory they allocate.

So, really, the answer is "no" unless you're prepared to do a *lot* of
work.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jan 1 '08 #2

Ivan Novick
P: n/a
Ivan Novick
On Jan 1, 7:12 am, Khookie <chris.k...@gmail.comwrote:
Hi all
>
I was wondering whether there was a way to know whether a pointer (in
my case, I'm using a char pointer) has been allocated memory through
malloc or not, thus needing to be freed at a later stage?
I am assuming you don't want to know where the memory for the actual
pointer comes from but you want to know where the memory pointed to by
the pointer comes from .... right?

First of all, given a memory address you don't even know if the
address is to memory that has been allocated at all... let alone from
where it was allocated. If I told you it was allocated... you
wouldn't know how much memory was allocated starting at that point.

So as Richard said, the answer is no, you actually need to keep track
of that your self (or use something fancy like a memory pool) when
coding in C.

Regards,
Ivan Novick
http://www.0x4849.net

Jan 1 '08 #3

Post your reply

Help answer this question



Didn't find the answer to your C / C++ question?

You can also browse similar questions: C / C++