473,804 Members | 3,067 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

some queries on freeing memory allocated using malloc

Hi,
(1)if i do the memory allocation like:
int **p;
p= malloc(n*sizeof p);
for(i=0;i<n;i++ ) /* i and n are integers */
p[i]= malloc(n*sizeof p);

then in that case is this command sufficient to free all the allocated
memory:

free(p);

or do i need to free it like this:

for(i=0;i<n;i++ )
free(p[i]);
free(p);

(2)
consider this:
func1(...)
{
...
...
for(i=0;i<n;i++ ){
p=func2(...) /* p is an integer pointer */
...
...
}
...
}/* end func1 */

int *func2(...)
{
int *P;
p= malloc(n*sizeof p);
...
...
return(p);
}/* end func2 */

in the above pseudo code where should i free the memory which has been
allocated in func2, supposing that n is significantly large. should it
be every time just before the call to func2 or at the end of func1 or
after return(p) in func2 itself.

thanks,
hassan
Nov 13 '05 #1
3 2581
Hassan Iqbal <iq**********@e xtenprise.net> scribbled the following:
Hi,
This question comes up fairly regularly here.
(1)if i do the memory allocation like:
int **p;
p= malloc(n*sizeof p);
for(i=0;i<n;i++ ) /* i and n are integers */
p[i]= malloc(n*sizeof p); then in that case is this command sufficient to free all the allocated
memory: free(p);
No it isn't.
or do i need to free it like this:

for(i=0;i<n;i++ )
free(p[i]);
free(p);
Yes you do.
(2)
consider this:
func1(...)
{
...
...
for(i=0;i<n;i++ ){
p=func2(...) /* p is an integer pointer */
...
...
}
...
}/* end func1 */ int *func2(...)
{
int *P;
p= malloc(n*sizeof p);
...
...
return(p);
}/* end func2 */ in the above pseudo code where should i free the memory which has been
allocated in func2, supposing that n is significantly large. should it
be every time just before the call to func2 or at the end of func1 or
after return(p) in func2 itself.


It should be in the code in func1(). If you add the free(p) code in
func2() after the return(p), it will never get executed, resulting in
memory leaks. Code after a return statement is *never* executed, no
matter what code it is, or which function it appears in.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Immanuel Kant but Genghis Khan."
- The Official Graffitist's Handbook
Nov 13 '05 #2
Hassan Iqbal wrote:
(1)if i do the memory allocation like:
int **p;
p= malloc(n*sizeof p);
We'll give you the benefit of the doubt (for code written instead of
copy-pasted), but the statement above will not exactly do what you expect.

p = malloc(n * sizeof *p);
for(i=0;i<n;i++ ) /* i and n are integers */
p[i]= malloc(n*sizeof p);
Same here: p[i] = malloc(n * sizeof **p);

for(i=0;i<n;i++ )
free(p[i]);
free(p);
That's what you need to free it all, indeed.
in the above <snipped> pseudo code where should i free the memory which has been
allocated in func2, supposing that n is significantly large. should it
be every time just before the call to func2 or at the end of func1 or
after return(p) in func2 itself.

You are quite free to free p wherever between the place it is allocated
at, and the place you last use it. The extreme last place where you can
free p is when it goes out of scope, likely when you are going to leave
the block (between the { and the } ) where p has been declared.

--
Bertrand Mollinier Toublet
Blog: http://www.bmt.dnsalias.org/blog

Nov 13 '05 #3


Hassan Iqbal wrote:
Hi,
(1)if i do the memory allocation like:
You are allocating a multidimensiona l array of type int. You
need to get the sizes correct. Look at the faq question 6.16
located at http://www.eskimo.com/~scs/C-faq/q6.16.html
int **p;
p= malloc(n*sizeof p);
p = malloc(n*sizeof *p); /* or n*sizeof(int *) */
for(i=0;i<n;i++ ) /* i and n are integers */
p[i]= malloc(n*sizeof p);
p[i] = malloc(n * sizeof **p); /* or n*sizeof(int) */

then in that case is this command sufficient to free all the allocated
memory:

free(p);
This is wrong.

or do i need to free it like this:

for(i=0;i<n;i++ )
free(p[i]);
free(p);
This is correct way to free the allocations.
(2)
consider this:
func1(...)
{
...
...
for(i=0;i<n;i++ ){
p=func2(...) /* p is an integer pointer */
...
...
}
...
}/* end func1 */

int *func2(...)
{
int *P;
p= malloc(n*sizeof p);
...
...
return(p);
}/* end func2 */

in the above pseudo code where should i free the memory which has been
allocated in func2, supposing that n is significantly large. should it
be every time just before the call to func2 or at the end of func1 or
after return(p) in func2 itself.


You are allocating the space in func2 which is returning a pointer
to the allocated space. You will then use this space in func1 for
some purpose. Once you are finished using the space then
deallocate (free) it. Beware for the hazards in func2 should there
be a allocation failure. In the case you will need to recover from
the allocation failure and signal func2 of the failure. This is
usually done by func2 returning NULL.

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
22979
by: disco | last post by:
I am working on this example from a book "C Primer Plus" by Prata 4th edition - p. 672. There is no erata on this problem at the publisher's website. 1) Is it a violation of copyright laws to post example code from a book to a newsgroup? 2) The program crashes as it tries to free memory and I would like to know the best way to correct THIS section of the code. By assigning current = head, current now points to the first structure in...
11
2306
by: binaya | last post by:
Dear all, Say I allocate a block of memory using the command malloc.I have a question. Can I deallocate certain portion of it only during runtime ? For eg: Say I allocate 5 pointers to int as below.
193
9656
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I speak only of features in the spirit of C; something like object-orientation, though a nice feature, does not belong in C. Something like being able to #define a #define would be very handy, though, e.g: #define DECLARE_FOO(bar) #define...
7
2219
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
7
1261
by: Emmet Caulfield | last post by:
In the course of examining the code for an Internet-connected authentication server, I came across the following code (twice in one function with different constants in the "if") in a file of some 2000 non-comment lines written by a "C" expert: if( elem->tag == SOME_MANIFEST_CONSTANT ) /* Alt */ { char *tempValue = malloc(32); strcpy(tempValue, elem->value); while( tempValue == '0' )
1
1383
by: skg | last post by:
I am passing the address of pointer like char** from managed extension and getting the its initialized value from a C library dll. How can i free the memory from the code in Managed Extension ? Here is a sample C function i am calling from managed extension. C dll Code ==============
20
1397
by: Tommy Vercetti | last post by:
Hi - Great group! I have 2 queries about undefined behavior: 1) Is the following code undefined? float myfunction(float f) {
66
3715
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
25
4741
by: Andreas Eibach | last post by:
Hi again, one of the other big woes I'm having... typedef struct perBlockStru /* (structure) Long words per block */ { unsigned long *lword; } lwperBlockStru_t;
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9569
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10318
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10302
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2975
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.