473,398 Members | 2,525 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

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

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
12 1929
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
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
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
"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
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
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
"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
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
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
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
"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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: benevilent | last post by:
Hey, I'm trying to debug the memory allocation in an embedded use of the Python interpreter. The longer I leave my program running the more memory it consumes. The total number of objects in...
14
by: dumboo | last post by:
hi there i m little bit confused over the following problem, i have understood wt the following code is doing...but not able to get the actual techinical stuff.....i have had a lot of hot debate...
5
by: CViniciusM | last post by:
Hello, The output of the code below is: number = 10 number = 0 (or other number except 15) Why the output of the second 'number' is not 15? Why the 'number' address is not changed? Thanks...
30
by: jimjim | last post by:
Hello, This is a simple question for you all, I guess . int main(){ double *g= new double; *g = 9; delete g; cout<< sizeof(g)<<" "<<sizeof(double)<<" "<<sizeof(*g)<<" "<<*g<<" "<<endl; *g =...
72
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
10
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions:...
3
by: Frank Rizzo | last post by:
It is common knowledge that 32-bit processes can use up to 2GB of RAM. This has been my experience with native (vb6, c++) apps. However, .NET apps tend to crash with Out of Memory errors whenever...
10
by: somenath | last post by:
Hi All, I was trying to understand the pass by value mechanism in c. To understand it I wrote a Small code as mentioned bellow. #include<stdio.h> #include<stdlib.h> #include<string.h> void...
11
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.