By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,992 Members | 934 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,992 IT Pros & Developers. It's quick & easy.

Is it ok to pass 'memory address' to free()

P: n/a
FI
Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
freeing memory this way is corrupting the heap.
Can anybody guide me on this.

Thanks in advance
DSKR

Aug 17 '06 #1
Share this Question
Share on Google+
12 Replies


P: n/a
On 17 Aug 2006 02:57:28 -0700, "FI" <fi**********@myrealbox.com>
wrote:
>Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
freeing memory this way is corrupting the heap.
Can anybody guide me on this.
The answer to your question could be yes, but without seeing your
code, it's hard to tell. If you can, post a minimal snippet of source
code that produces the problem.

The following is Standard C, regardless of whether malloc() returns
NULL or not:

#include <stdlib.h>
extern size_t n;
int main(void)
{
void *p = malloc(n);
free(p);
return 0;
}

Best regards
--
jay
Aug 17 '06 #2

P: n/a
FI wrote:
Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
freeing memory this way is corrupting the heap.
Can anybody guide me on this.
You can only pass it NULL or a value you got from
malloc,calloc or realloc.
Aug 17 '06 #3

P: n/a
FI wrote:
Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
freeing memory this way is corrupting the heap.
Can anybody guide me on this.
We probably could. Post the code, not a vague description of the code.


Brian
Aug 17 '06 #4

P: n/a
"FI" <fi**********@myrealbox.comwrote in message
news:11**********************@b28g2000cwb.googlegr oups.com...
Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
freeing memory this way is corrupting the heap.
Can anybody guide me on this.
Without seeing the code in question, it's hard to say, but in most cases
when the "heap" is corrupted, it means either (a) you're writing outside the
bounds of the objects you allocate, confusing free(), or (b) you're somehow
modifying the pointers you get back from malloc() and then passing something
different to free(), also confusing it.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 17 '06 #5

P: n/a
On 17 Aug 2006 02:57:28 -0700, "FI" <fi**********@myrealbox.com>
wrote:
>Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and
If you have an array of pointers to int, the each element of that
array is in fact a pointer variable. Since C passes arguments by
value, it makes no difference to free if the argument is a scalar
pointer or part of an aggregate. The important thing is that the
argument be of a type compatible with the prototype (free expects a
void* so any pointer type satisfies this requirement) and that the
value is the exact value returned from m/c/realloc and not previously
passed to free.
>freeing memory this way is corrupting the heap.
Not likely but we need to see your code to be sure.
Remove del for email
Aug 18 '06 #6

P: n/a
FI
Thank you all for the responses.

Hello Barry,
You got my problem clearly...and I feel that I have been doing the same
thing you suggested...copied below is the code snippet(I am using Win32
Memory Management API)...please let me know where am I going wrong.
//Declaration of 'Array of Pointers' to hold return values from
HeapAlloc
void* APtrAry[MAX_CMD];
//Inside a function where I alloc memory
void functionname(void)
{
//Free all previously allocated memory, if any
for(i=0;i<MAX_CMD;i++)
{
if(APtrAry[i] 0)

if(!HeapFree(GetProcessHeap(),0,(LPVOID)&ASnrIPtrA ry[i]))
PrintErr(TEXT("HeapFree() Failed"));
}

//Clear the array of pointers
ZeroMemory(APtrAry,sizeof(APtrAry[MAX_CMD]));

//Clear the structure that is initialised with the pointers
allocated below
ZeroMemory(pICMDRs,sizeof(pICMDRs[MAX_CMD]));
//Alloc memory and store the 'memory address' returned into array
elements
APtrAry[i] = (unsigned char
*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,SIZE _OF_MEMORY);

//Update the pointer to memory into an element of another
structure
pICMDRs[i] = ASnrIPtrAry[i];
//I am using this global structure in a seperate function
}

HeapFree() in the loops fails in the second iteration...I mean if 3
allocations were made ...HeapFree() is successful in freeing memory
pointed to by the first element of array...but fails in second
iteration.
Thanks & Regards,
DSKR
Barry Schwarz wrote:
On 17 Aug 2006 02:57:28 -0700, "FI" <fi**********@myrealbox.com>
wrote:
Hello All,
I am relatively new to C programming and I am struck with a problem in
dynamic memory allocation.
I would like to know if it is ok to pass the 'memory address' returned
by malloc()(stored not in a pointer variable but as an element of an
array of type int*) directly to free(). My program allocating and

If you have an array of pointers to int, the each element of that
array is in fact a pointer variable. Since C passes arguments by
value, it makes no difference to free if the argument is a scalar
pointer or part of an aggregate. The important thing is that the
argument be of a type compatible with the prototype (free expects a
void* so any pointer type satisfies this requirement) and that the
value is the exact value returned from m/c/realloc and not previously
passed to free.
freeing memory this way is corrupting the heap.

Not likely but we need to see your code to be sure.
Remove del for email
Aug 18 '06 #7

P: n/a
"FI" <fi**********@myrealbox.comwrites:
Thank you all for the responses.

Hello Barry,
You got my problem clearly...and I feel that I have been doing the same
thing you suggested...copied below is the code snippet(I am using Win32
Memory Management API)...please let me know where am I going wrong.
You're going wrong in at least two ways.

1. You're top-posting. Please read
<http://www.caliburn.nl/topposting.htmlfor more information.

2. You're using the Win32 Memory Management API. Not that there's
necessarily anything wrong with that, but we really can't help you
with it here. Either write your code to use the standard C memory
allocation functions (malloc, calloc, realloc, free), or ask about it
in a Windows-specific newsgroup.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 18 '06 #8

P: n/a
On Thu, 17 Aug 2006 21:01:08 -0700, FI wrote:
Thank you all for the responses.
Don't top post, thanks.
//Declaration of 'Array of Pointers' to hold return values from HeapAlloc
void* APtrAry[MAX_CMD];

//Inside a function where I alloc memory void functionname(void)
{
//Free all previously allocated memory, if any
for(i=0;i<MAX_CMD;i++)
{
if(APtrAry[i] 0)

if(!HeapFree(GetProcessHeap(),0,(LPVOID)&ASnrIPtrA ry[i]))
PrintErr(TEXT("HeapFree() Failed"));
}
}
//Clear the array of pointers
ZeroMemory(APtrAry,sizeof(APtrAry[MAX_CMD]));
If this line is useful, it's wrong. It appears that you intend
to zero all of the pointers in APtrAry. If you immediately exit
your program, the error is harmless. If you continue to execute
code presuming that the free()d pointers are NULL, they won't be.

The big error is that sizeof(APtrAry[MAX_CMD]) is equal to
sizeof(APtrAry[0]), ie, the size of a single entry. It's an
obscure error that the standard doesn't guarantee all-bits-zero
equalling the NULL pointer, though that's unlikely on your system.

I would recommend deleting the line "ZeroMemory(...);" and adding a
line "APtrAry[i] = NULL;" after the line "if(!HeapFree...)".

Martin
--
Martin Golding DoD #0236 | fo*****@comcast.net
Always code as if the person who ends up maintaining your code will be a
violent psychopath who knows where you live.

Aug 18 '06 #9

P: n/a
On 17 Aug 2006 21:01:08 -0700, "FI" <fi**********@myrealbox.com>
wrote:
>Thank you all for the responses.

Hello Barry,
You got my problem clearly...and I feel that I have been doing the same
thing you suggested...copied below is the code snippet(I am using Win32
Memory Management API)...please let me know where am I going wrong.
//Declaration of 'Array of Pointers' to hold return values from
HeapAlloc
void* APtrAry[MAX_CMD];
//Inside a function where I alloc memory
void functionname(void)
{
//Free all previously allocated memory, if any
for(i=0;i<MAX_CMD;i++)
{
if(APtrAry[i] 0)
I don't know if is portably defined for void*. You can achieve the
same result with an unambiguous
if (APtrAry[i] != NULL)
or the equivalent (but to my mind less intuitive)
if (APtrAry[i])
>
if(!HeapFree(GetProcessHeap(),0,(LPVOID)&ASnrIPtr Ary[i]))
PrintErr(TEXT("HeapFree() Failed"));
}
I don't know what this function does but it doesn't involve the value
tested in the if.
>
//Clear the array of pointers
ZeroMemory(APtrAry,sizeof(APtrAry[MAX_CMD]));
sizeof is an operator, not a function. The parentheses are
superfluous if the operand is an object (as opposed to a type).

All bits zero is not necessarily the representation of a void* set to
NULL. If you want to clear the array, you need sizeof APtrAry. sizeof
APtrAry[MAX_CMD] is the size of one element of the array; it doesn't
matter what value you put in the brackets since the operand is not
evaluated.

But the portable solution is to put a statement like
APtrAry[i] = NULL;
in the previous for loop after calling HeapFree.
>
//Clear the structure that is initialised with the pointers
allocated below
ZeroMemory(pICMDRs,sizeof(pICMDRs[MAX_CMD]));
//Alloc memory and store the 'memory address' returned into array
elements
APtrAry[i] = (unsigned char
*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,SIZ E_OF_MEMORY);
Since APtrAry[i] is a void*, why are you casting to unsigned char*?
More to the point, why are you casting at all?
>
//Update the pointer to memory into an element of another
structure
pICMDRs[i] = ASnrIPtrAry[i];
What is ASnrIPtrAry?
//I am using this global structure in a seperate function
}

HeapFree() in the loops fails in the second iteration...I mean if 3
allocations were made ...HeapFree() is successful in freeing memory
pointed to by the first element of array...but fails in second
iteration.

Remove del for email
Aug 19 '06 #10

P: n/a
Barry Schwarz <sc******@doezl.netwrites:
On 17 Aug 2006 21:01:08 -0700, "FI" <fi**********@myrealbox.com>
wrote:
[...]
>>void functionname(void)
{
//Free all previously allocated memory, if any
for(i=0;i<MAX_CMD;i++)
{
if(APtrAry[i] 0)

I don't know if is portably defined for void*.
I was about to say that it isn't, but it turns out that it is.
Given:
void *ptr1, *ptr2;
the expression (ptr1 < ptr2) is meaningful as long as both point into,
or just past the end of, the same object.

If they don't (including the case where one is a null pointer), the
behavior is undefined.

A pointer to an object is not "less than" or "greater than" a null
pointer; it's either equal or unequal.
You can achieve the
same result with an unambiguous
if (APtrAry[i] != NULL)
or the equivalent (but to my mind less intuitive)
if (APtrAry[i])
Right.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 19 '06 #11

P: n/a
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
Barry Schwarz <sc******@doezl.netwrites:
>I don't know if is portably defined for void*.

I was about to say that it isn't, but it turns out that it is.
Given:
void *ptr1, *ptr2;
the expression (ptr1 < ptr2) is meaningful as long as both point into,
or just past the end of, the same object.

If they don't (including the case where one is a null pointer), the
behavior is undefined.

A pointer to an object is not "less than" or "greater than" a null
pointer; it's either equal or unequal.
Lest someone point out that this works on most modern machines with a
flat memory model, there is a glaring exception: AMD64. On that
platform, you can reliably compare pointers from different objects, but
testing ptr>0 is still incorrect because pointers are _signed_ (i.e. a
valid pointer can be negative). One could say that's an evil system
design, but there's a good reason for it.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 20 '06 #12

P: n/a

Stephen Sprunk wrote:
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
Barry Schwarz <sc******@doezl.netwrites:
I don't know if is portably defined for void*.
I was about to say that it isn't, but it turns out that it is.
Given:
void *ptr1, *ptr2;
the expression (ptr1 < ptr2) is meaningful as long as both point into,
or just past the end of, the same object.

If they don't (including the case where one is a null pointer), the
behavior is undefined.

A pointer to an object is not "less than" or "greater than" a null
pointer; it's either equal or unequal.

Lest someone point out that this works on most modern machines with a
flat memory model, there is a glaring exception: AMD64. On that
platform, you can reliably compare pointers from different objects, but
testing ptr>0 is still incorrect because pointers are _signed_ (i.e. a
valid pointer can be negative). One could say that's an evil system
design, but there's a good reason for it.
Are you making a point about a C implementation? Do
(some) C compilers on AMD64 compare pointers using signed
comparison? Certainly they wouldn't have to.

Aug 24 '06 #13

This discussion thread is closed

Replies have been disabled for this discussion.