How to Use malloc

How to Use malloc - How to Use malloc. Let's say that you...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
How to Use malloc. .. Let's say that you would like to allocate a certain amount of memory during the execution of your program. You can call the malloc function at any time, and it will request a block of memory from the heap. The system will reserve a block of memory for your program, and you can use it in any way you like. When you are done with the block, you return it to the system heap for recycling by calling the free function. Then other applications can reserve it later for their own use. For example, #include int main() { int *p; p = (int *)malloc(sizeof(int)); if (p == 0) { printf("ERROR: Out of memory\n"); return 1; } *p = 5; printf("%d\n", *p); free(p); return 0; } The first line in this program calls the malloc function. This function does three things: 1. The malloc statement first looks at the amount of memory available on the heap and asks, "Is there enough memory available to allocate a block of memory of the size requested?" The amount of memory needed for the block is known
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

How to Use malloc - How to Use malloc. Let's say that you...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online