why do we have to use malloc,calloc funtion?

Thread Starter

Werapon Pat

Joined Jan 14, 2018
35
I start learning and writing binary tree and I wonder if we define some variables does it just allocate the memory from ram by itself?
and we can even print its address out(by using &) that means it already has its own memory somewhere on our ram so I realized.
why do we have to use malloc,calloc function to allocate the memory again?

upload_2018-3-20_2-0-2.png
 

dl324

Joined Mar 30, 2015
16,839
Code fragment without extraneous information, colors reversed for readability:
upload_2018-3-19_12-17-6.png
When you declare variables in your code, the compiler will allocate memory for them.

You use malloc/calloc when you don't want, or can't have, the compiler allocate memory. For instance, your binary tree. Why allocate memory for branches that might not be used? It's more efficient to allocate storage as you need it.

Malloc allocates a block of memory at runtime, but it doesn't clear it; that's what calloc does. When you allocate memory, you should free it before your program exits. Depending on something to do it for you isn't good practice.
 

WBahn

Joined Mar 31, 2012
29,976
I start learning and writing binary tree and I wonder if we define some variables does it just allocate the memory from ram by itself?
and we can even print its address out(by using &) that means it already has its own memory somewhere on our ram so I realized.
why do we have to use malloc,calloc function to allocate the memory again?

View attachment 148664
It's a bit hard to tell exactly what you are asking -- and I suspect that's because you don't really know what it is you should be asking at this point. So I'm going to have to do a bit of guessing.

When you declare a variable such as

int fred;

the compiler allocates memory to store a variable of type int and associates the name fred with the address of that block of memory where the int is stored. However, the compiler does NOT initialize the contents of that variable, so it is basically random garbage. This means that the integer value stored in fred is a random integer.

When you declare a variable such as

int *sue;

the compiler allocates memory to store a variable of type int * (a pointer to a value of type int) and associates the name sue with the address of that block of memory where the pointer is stored. However, the compiler does NOT initialize the contents of that variable, so it is basically random garbage. This means that the address stored in sue is a random address.

Note that the compiler also has not allocated any memory for the int value that sue is expected to point to.

Nothing changes with the type of value being pointed to is a structure instead of an int.

Node *Left;

only allocates memory in which to store an address and it will be assumed that this address is that of a Node structure. It will NOT allocate memory for a Node structure. Furthermore, the variable Left is not initialized, so it will start out with a random value and you will be unable to distinguish between this random value and a valid memory address at which a Node structure is actually stored. This is why it is extremely good practice to always initialize pointer variables to NULL upon declaration because that IS a value you can check for in order to determine if it is a valid pointer value or not.

You call malloc() or calloc() in order to allocate memory for your data. The function returns the address of the block where it was placed and you need to store that address in the pointer.

When you are done using memory, it is important to free them. In this case, you need to free EACH node that got allocated. It is NOT sufficient to just clear the top level node (your tree). If you do that, you will lose all of your references to all of the other nodes, but the memory will still be allocated and therefore unavailable for anything else. This is known as a memory leak.
 

Papabravo

Joined Feb 24, 2006
21,158
On a more basic level you don't have to do anything except die and pay taxes. If you choose not to use the library functions malloc() and calloc() you are certainly free to ignore them; but you then must find another way to provide the function they perform or the likely result in your program will be a difficult to debug sort of chaos where you have no clue where your variables are or where the pointers point.
 

Ian Rogers

Joined Dec 12, 2012
1,136
You can just think it through... I almost never use malloc();.. It was designed specifically for dynamic memory allocation.. On the fly.

Most uses of memory are known... If you are programming something like a PC odds on you have tons of memory at your disposal...
Once it wasn't the case and we had to mess around with only 640k and a sizeable amount of that was used by device drivers..

One thing though! If you don't free up the memory your application uses, you have a memory leak and a reboot is the only way to get it back.
I'm not sure if free(); works with memory not allocated by malloc();
 

WBahn

Joined Mar 31, 2012
29,976
You can just think it through... I almost never use malloc();.. It was designed specifically for dynamic memory allocation.. On the fly.

Most uses of memory are known... If you are programming something like a PC odds on you have tons of memory at your disposal...
So how much memory would you allocate statically if you are making a word processor?

How much memory would you allocate statically if you are making an electronic gradebook?

How much memory would you allocate statically if you are analyzing a circuit netlist or a PCB layout?

Most meaningful programs of any complexity involve data sets of arbitrary size that are unknown at compile time.

One thing though! If you don't free up the memory your application uses, you have a memory leak and a reboot is the only way to get it back.
Not true. When your program ends, all of the memory that the OS assigned to it is freed. So as long as you can kill the program, any memory you were using with it will be freed up. Now, if the OS has a memory leak, the same thing applies. However, the only way to end the OS and recover the memory is to reboot it.

I'm not sure if free(); works with memory not allocated by malloc();
No (unless we are talking about the other functions in the malloc() such as calloc() and realloc(), but those usually allocated memory via an internal call to malloc()).

When needed, the compiler includes a memory manager as part of your program and malloc() and free() are interface functions to that manager.

Besides, what other memory is there that COULD be freed?

The only possibility would be the automatic memory on the stack, and that is deallocated automatically (hence the name).

Off the top of my head, I believe all other memory is static and of program lifetime.

I'm assuming, of course, that we are only talking about C.
 

Ian Rogers

Joined Dec 12, 2012
1,136
Not true. When your program ends, all of the memory that the OS assigned to it is freed.
Hey! we're talking about windows here!! Windows has never been good at freeing memory.. Most books / technical papers ask you to expcicitly free memory used.. If the TS is asking this question, I very much doubt he's going to do a word processor or database!!

FWIW.. Microsoft allocates 40% of available memory for some of its app no matter how much you shove in..
I'm assuming, of course, that we are only talking about C
Going off the picture he's using C++
 

WBahn

Joined Mar 31, 2012
29,976
Hey! we're talking about windows here!! Windows has never been good at freeing memory..
I'm pretty sure that every OS has had memory leaks, though Windows has historically been the worst. I don't know what the status is on current versions of the OS's.

I know that even back in the WinNT4 days I would frequently leave my computer running for months (and, in the case of one computer, over five years) without rebooting it.

Memory leaks in the OS are independent of memory leaks in your program due to not freeing dynamically allocated memory. Any leaks due to how the OS handles running your program will be unaffected by what you do internal to your program -- as far as the OS is concerned, it gave your program a certain chunk of memory and it neither knows no cares how you use it and it's going to reclaim that chunk when it terminates your program. Now, I'm talking about self-contained programs. If you start throwing interprocess communication and other things in the mix, it is not as simple and I don't even want to think about that right now.

Most books / technical papers ask you to expcicitly free memory used..
You most definitely should free memory that you use. The only time when not doing so is really justified is when you are at a point that you are exiting the program. Even then it is very good practice to do so from a maintainability standpoint to prevent you from, for example, adding code to recover from a situation that you previously just died gracefully for. If your prior code just exited and relied on the OS freeing the memory, you can easily create a memory leak in your program that will eventually cause it to crash.

If the TS is asking this question, I very much doubt he's going to do a word processor or database!!
Fine. How much memory should the TS statically allocate for his tree?

Going off the picture he's using C++
I think it's the same thing as far as this discussion is concerned, but clarifying that is worthwhile.
 

Ian Rogers

Joined Dec 12, 2012
1,136
ine. How much memory should the TS statically allocate for his tree?
Only he knows... But the NODE only contains an int and two pointers ( 10 bytes).. So theoretically 1000 entries wont take up much space!

BUT!! I suppose he needs to learn dynamic allocation.. And!! being Windows it would be safer!

EDIT... Might be 64 bit pointers.. Make that 18 bytes..
 

eetech00

Joined Jun 8, 2013
3,856
I start learning and writing binary tree and I wonder if we define some variables does it just allocate the memory from ram by itself?
and we can even print its address out(by using &) that means it already has its own memory somewhere on our ram so I realized.
why do we have to use malloc,calloc function to allocate the memory again?

View attachment 148664
Hi

The short answer is that Malloc and Calloc allow the program to allocate and release memory dynamically. If you declare a variable statically then the memory allocated for the variable is retained as long as the program is running. Not a big deal if there are not many variables. But...memory is not released..so other programs do not have access to that memory space.

eT
 

WBahn

Joined Mar 31, 2012
29,976
Only he knows... But the NODE only contains an int and two pointers ( 10 bytes).. So theoretically 1000 entries wont take up much space!

BUT!! I suppose he needs to learn dynamic allocation.. And!! being Windows it would be safer!

EDIT... Might be 64 bit pointers.. Make that 18 bytes..
So let's say he takes your advice and statically allocates memory for 1000 entries. What happens the first time he needs 1001 entries (which is not that big a tree when all is said and done)? He has to modify and recompile his program.

Please explain how being Windows has anything to do with whether or not he should use dynamic memory allocation and why dynamic allocation is safer in Windows as opposed to more risky.
 

MrSoftware

Joined Oct 29, 2013
2,188
I start learning and writing binary tree and I wonder if we define some variables does it just allocate the memory from ram by itself?
and we can even print its address out(by using &) that means it already has its own memory somewhere on our ram so I realized.
why do we have to use malloc,calloc function to allocate the memory again?

View attachment 148664
Your Tree_PTR T is just a pointer, print the sizeof(T) and sizeof(Tree_NODE) and notice how they are different. The part of the IDE that expands variables is expanding "T", but it doesn't understand that memory for the struct itself has not been allocated yet. If you print the values stored in T->data, T->Left and T->Right before the malloc(), you're just going to get complete junk. The only memory allocated at that point is for a pointer, not the struct, and the value stored in the pointer T points to some random place according to whatever was in memory when T was allocated. Actually it should cause an exception because memory for those elements hasn't been allocated yet. Also the pointer "T" is allocated on the stack, it will disappear when that function returns. But the memory allocated in malloc() is allocated on the heap, and it will still be allocated after the function returns. So the pointer "T" is temporary, and it temporarily stores the address returned by malloc(). The function will return the address that is stored in T so that the caller receives the address of the allocated memory, but the memory for the pointer "T" itself will be gone. Does this help?
 

Ian Rogers

Joined Dec 12, 2012
1,136
So let's say he takes your advice and statically allocates memory for 1000 entries. What happens the first time he needs 1001 entries (which is not that big a tree when all is said and done)? He has to modify and recompile his program.

Please explain how being Windows has anything to do with whether or not he should use dynamic memory allocation and why dynamic allocation is safer in Windows as opposed to more risky.
Enough!! I'm not in the club... I get it..

Happened 8 years ago as well...
 

miniwinwm

Joined Feb 2, 2018
68
I almost never use malloc...
And neither do I - can't remember the last time I did. It depends entirely on the system the code is being developed for. On small 8 bit systems you can't allocate memory when the functionality is not available. On larger safety critical systems often it's not allowed. And on deeply embedded single application systems it's usually not necessary because at compile time you know how much you need of everything anyway. Simple RTOS's used in SC applications will never leak memory, because they don't allocate it dynamically either.
 
Top