954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Malloc/Calloc Dynamic Memory Allocation.

Can someone please explain to me how dynamic memory allocation actually works? For example whast going on in the piece of code written below? If you can respond asap, that would be great. Thanks in advance.

p = (float *) malloc ( n * sizeof( float ));


And whats the difference in malloc and calloc?

warpstar
Newbie Poster
17 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

>>And whats the difference in malloc and calloc?
calloc() calls malloc() then initializes the data to all 0s.

The code you posted is allocating an array of n floats

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

whats the difference in malloc and calloc/?

Can someone please explain to me how dynamic memory allocation actually works? For example whast going on in the piece of code written below? If you can respond asap, that would be great. Thanks in advance.

p = (float *) malloc ( n * sizeof( float ));

And whats the difference in malloc and calloc?

warpstar
Newbie Poster
17 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 
>>And whats the difference in malloc and calloc? calloc() calls malloc() then initializes the data to all 0s.


Please read answers given to you. And don't quote yourself...

A computer program is loaded into several parts of memory. There is the code (functions and the like), data (global variables and the like), the stack (local variables and the like), and theheap.

The heap is just a big block of unused memory that your program is allowed to use. When you call malloc() it takes a chunk of the heap and marks it as 'allocated', and returns a pointer to the part of the heap memory you can use. When you call free() that piece of heap memory is unmarked and available for malloc() to use again.

So for your example, you ask for n *sizeof( float ) bytes of the heap. The pointer p points to the first part of the heap you are allowed to use for your array of floats.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

http://c-faq.com/malloc/calloc.html
Note in particular that using calloc to initialise your floats to 0.0 is NOT portable.

Also, since this is C++, you should really be using
p = new float[n];

If this were a C program, I would be telling you NOT to cast the result of malloc.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You