473,322 Members | 1,347 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,322 software developers and data experts.

malloc questions in C

if I use malloc() in a function to allocate a space for my array of
structures. I didn't free() them anywhere in the program.
I found that I can still use that space after I come back to main().

Am I supposed to use that space or it is temporary and will be removed
soon afterwards?

Thanks

Jan 21 '06 #1
9 1742
questions? a écrit :
if I use malloc() in a function to allocate a space for my array of
structures. I didn't free() them anywhere in the program.

I found that I can still use that space after I come back to main().

Am I supposed to use that space or it is temporary and will be removed
soon afterwards?


The duration of an allocated bloc starts when malloc() returns a
non-NULL value (aka a valid block address) and ends when free() is
invoked (with the value returned by the corresponding malloc().

--
A+

Emmanuel Delahaye
Jan 21 '06 #2
Ico
questions? <un************@hotmail.com> wrote:
if I use malloc() in a function to allocate a space for my array of
structures. I didn't free() them anywhere in the program.
I found that I can still use that space after I come back to main().
That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.
Am I supposed to use that space or it is temporary and will be removed
soon afterwards?


You are supposed to give back the memory to the system with free() when
you no longer need the memory, or at least before your program
terminates.

--
:wq
^X^Cy^K^X^C^C^C^C
Jan 21 '06 #3

Ico wrote:
questions? <un************@hotmail.com> wrote:
if I use malloc() in a function to allocate a space for my array of
structures. I didn't free() them anywhere in the program.
I found that I can still use that space after I come back to main().


That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.


So, with malloc() function, it is static regardless in the sense that
whether you are in main or in a function, it is permanant,right?


Am I supposed to use that space or it is temporary and will be removed
soon afterwards?


You are supposed to give back the memory to the system with free() when
you no longer need the memory, or at least before your program
terminates.

--
:wq
^X^Cy^K^X^C^C^C^C


Jan 21 '06 #4
questions? wrote:
Ico wrote:
questions? <un************@hotmail.com> wrote:
if I use malloc() in a function to allocate a space for my array of
structures. I didn't free() them anywhere in the program.
I found that I can still use that space after I come back to main().


That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.


So, with malloc() function, it is static regardless in the sense that
whether you are in main or in a function, it is permanant,right?


There are three kinds of storage durations: automatic, static and
allocated. So, "static" is probably the wrong term to use.

Static storage duration: The object exists before main() is entered
the first time till the end of the programme. It is always initialised
(default: zero of the appropriate type).
Automatic storage duration: The object begins life starting at its
declaration to the end of the scope it has been declared in.
Allocated storage duration: The object begins life starting at the
successful call to malloc()/calloc()/realloc() and can be accessed
until it is free()d or until the end of the programme.

Example (not tested):

#include <stdlib.h>

int *GiveMeFive (void)
{
static int five = 5;
return &five;
}

int *GiveMeTen (void)
{
int *ten = malloc(*ten);
if (ten) {
*ten = 10;
}
return ten;
}

int *GiveMeNothing (void)
{
int nothing = 0;
return &nothing;
}

int main (void)
{
int *example = NULL;

example = GiveMeFive();
*example += 2; /* Okay. five is permanently changed. */

example = GiveMeTen();
if (example)
{
*example += 3; /* Okay; the storage returned at the first
* call of GiveMeTen() is permanently changed. */
example = GiveMeTen(); /* Memory leak: The storage written to
* above still exists and contains "13"
* but is no longer accessible. If example
* is != NULL, it contains the address of
* newly allocated storage.
*/
if (example) {
*example += 4;
free(example); /* Now ends the life of example */
}
}

example = GiveMeNothing() /* Error! nothing is no longer alive */

/* five and, if malloc() was successful, the first value of ten,
* are still alive. */

return 0;
}
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jan 22 '06 #5
"questions?" <un************@hotmail.com> writes:
Ico wrote:
questions? <un************@hotmail.com> wrote:
> if I use malloc() in a function to allocate a space for my array of
> structures. I didn't free() them anywhere in the program.
> I found that I can still use that space after I come back to main().


That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.


So, with malloc() function, it is static regardless in the sense that
whether you are in main or in a function, it is permanant,right?


"Static" isn't the right word for it.

The lifetime of a memory block allocated with malloc() doesn't depend
on where you call it.

There are three storage durations: "static" (for static or global
objects; these exist for the entire lifetime of the program),
"automatic" (for non-static objects declared locally to a function or
block; these cease to exist when the function or block finishes), and
"allocated" (for objects allocated by malloc(); these exist until
they're free()d).

Note that malloc() and free() aren't the only relevant functions, but
I'm too lazy to go into the details of calloc() and realloc().

And main() *is* a function. An object declared inside main() isn't
global; it's local to the function.

--
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.
Jan 22 '06 #6

Keith Thompson wrote:
"questions?" <un************@hotmail.com> writes:
Ico wrote:
questions? <un************@hotmail.com> wrote:
> if I use malloc() in a function to allocate a space for my array of
> structures. I didn't free() them anywhere in the program.
> I found that I can still use that space after I come back to main().

That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.


So, with malloc() function, it is static regardless in the sense that
whether you are in main or in a function, it is permanant,right?


"Static" isn't the right word for it.

The lifetime of a memory block allocated with malloc() doesn't depend
on where you call it.

There are three storage durations: "static" (for static or global
objects; these exist for the entire lifetime of the program),
"automatic" (for non-static objects declared locally to a function or
block; these cease to exist when the function or block finishes), and
"allocated" (for objects allocated by malloc(); these exist until
they're free()d).

Note that malloc() and free() aren't the only relevant functions, but
I'm too lazy to go into the details of calloc() and realloc().

And main() *is* a function. An object declared inside main() isn't
global; it's local to the function.

--
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.

Thank you all for the answer!!! It is really really helpful.

1) what is really a memory leak?
2) if I forgot to free a memory from malloc(), after termination of my
program. It will be returned back to system,right?

Jan 22 '06 #7
questions? wrote:
1) what is really a memory leak?
Allocating memory and not freeing it before the last pointer to it goes
out of scope or is reassigned. After the pointer has been reassigned,
the previously allocated memory is leaked as it can no longer be freed.
2) if I forgot to free a memory from malloc(), after termination of my
program. It will be returned back to system,right?

Right, assuming there is a system to return it to.

--
Ian Collins.
Jan 22 '06 #8
questions? a écrit :
1) what is really a memory leak?
When there is no way to free an allocated block. If you do that on 24/7
application (a server, for instance), you 'eat' the memory ressources
until the system crashes down.
2) if I forgot to free a memory from malloc(), after termination of my
program. It will be returned back to system,right?


Can't tell. It's a system issue.

--
A+

Emmanuel Delahaye
Jan 22 '06 #9
questions? wrote:
Keith Thompson wrote:
"questions?" <un************@hotmail.com> writes:
Ico wrote:

questions? <un************@hotmail.com> wrote:

>if I use malloc() in a function to allocate a space for my array of
>structures. I didn't free() them anywhere in the program.
>I found that I can still use that space after I come back to main().

That is how it is supposed to work. When you allocate memory with
malloc() or one of the similar functions, it will be available until you
call free(). A lot of C implementations will also free this memory for
you when your program exits, but don't count on that.

So, with malloc() function, it is static regardless in the sense that
whether you are in main or in a function, it is permanant,right?
"Static" isn't the right word for it.

The lifetime of a memory block allocated with malloc() doesn't depend
on where you call it.

There are three storage durations: "static" (for static or global
objects; these exist for the entire lifetime of the program),
"automatic" (for non-static objects declared locally to a function or
block; these cease to exist when the function or block finishes), and
"allocated" (for objects allocated by malloc(); these exist until
they're free()d).

Note that malloc() and free() aren't the only relevant functions, but
I'm too lazy to go into the details of calloc() and realloc().

And main() *is* a function. An object declared inside main() isn't
global; it's local to the function.


Thank you all for the answer!!! It is really really helpful.

1) what is really a memory leak?


Ask wikipedia or the jargon file
http://en.wikipedia.org/wiki/Memory_leak
http://www.catb.org/jargon/html/M/memory-leak.html
2) if I forgot to free a memory from malloc(), after termination of my
program. It will be returned back to system,right?


Yes, if your system does this. And as long as the usage of your
code does not change.
Imagine that you wrote a module and a "test" programme for it.
#include "myhappyfunmodule.h"

void test (void)
{
/* use myhappyfunmodule stuff */
/* a) myhappyfunmodule has an internal memory leak */
/* b) myhappyfunmodule returns allocated storage and
** test() does not free() it */
}
int main (void)
{

test();

return 0;
}
Now, one year after having written it, you want to use
myhappyfunmodule for a programme which runs for hours and
days in a loop. You thoughtlessly copy "test", throw out
main(), rename test() to runhappyfun(), change a couple
of things and try it out.
runhappyfun() is called millions of times and leaks a
couple of bytes every time; this effectively becomes a problem
over time as the programme eats your resources. You may have
to terminate it early/it dies by itself/it takes down your
system and valuable data.
Now, you have a look into runhappyfun(), find b), remove it.
Seems to work.
a) still leaks a few bytes at a time but maybe not always.
Then comes the one time it really counts and, sadly, a) eats
your memory once again and does Bad Things.
So, you have to debug your old code, find a) and fix it.
Maybe you even knew about the leaks when writing
myhappyfunmodule but thought "test() is only a test function,
I do not want to bother with deallocation" and "well, in a
very special situation, we have a leak (a)) but preventing
this costs ten lines extra which I always can do later",
respectively...
If you do it right from the beginning, you can save yourself
trouble further down the road.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jan 22 '06 #10

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

Similar topics

14
by: dam_fool_2003 | last post by:
Friends, cannot we malloc a array? So, I tried the following code: int main(void) { unsigned int y={1,3,6},i,j; for(i=0;i<3;i++) printf("before =%d\n",y); *y = 7; /* 1*/
11
by: Mannequin* | last post by:
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to...
9
by: zerro | last post by:
Hello, I try to understand heap overflows (under Linux), but can not understand one thing with freeing memory allocated with malloc(). Here it comes: I have a program called 1.c: main() {...
11
by: Gustavo G. Rondina | last post by:
Hi all I'm writting a simple code to solve an ACM problem (http://acm.uva.es, it is the problem #468). In its code I have the following fragment: freq = calcfreq(hashfreq, strfreq, input);...
7
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...
23
by: puzzlecracker | last post by:
Why is "new" a C++ language-level construct while "malloc" is a library function?
7
by: Alexandre | last post by:
Hello, Maybe it's a little OT, but the fact is that I don't necessarly want to know "how to correct?", but "why it happens?" I have a program who "segment fault" (ok, that's "normal"... ;-)...
17
by: Chen Shusheng | last post by:
Hi all, In fact, I want to let my memory run out. And see what will happen. My system is windowsXp. Memory is 256M.I think my cdes will apply more memory than I have. Codes are below: ...
3
by: Petr Pavlu | last post by:
Hello, I have two questions how the functions should be written. I read the FAQ but didn't find any answer. If there is any please point me out. I. Cleanup code Consider I have to open file1,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.