Allocate memory storage then freeing up

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Allocate memory storage then freeing up

To show: The malloc() & free() C functions - the dynamic memory allocation

 

/* Playing with free(), memory on the heap */

#include <stdio.h>

#include <stdlib.h>

 

void main(void)

{

int x;

int *y;

int *buffer = NULL;

 

/* do 100 times iteration, 100 blocks */

for(x=0; x<100; x++)

{

/* For every iteration/block, allocate 16K, system will truncate to the nearest value */

y = (int *)malloc(16384);

 

/* If there is a problem */

if(y == NULL)

{

puts("No more memory for allocation lol!");

/* exit peacefully */

exit(0);

}

 

/* Allocate the memory block, print the block and the address */

printf("Allocating-->block: %i address: %p\n", x, y);

printf("---->Freeing the memory block: %i address: %p\n", x, y);

free((void *)buffer);

}

}

 

Output example:

 

Allocating-->block: 0 address: 00355018

---->Freeing the memory block: 0 address: 00355018

Allocating-->block: 1 address: 00420068

---->Freeing the memory block: 1 address: 00420068

Allocating-->block: 2 address: 00424098

---->Freeing the memory block: 2 address: 00424098

Allocating-->block: 3 address: 004280C8

---->Freeing the memory block: 3 address: 004280C8

Allocating-->block: 4 address: 0042C0F8

---->Freeing the memory block: 4 address: 0042C0F8

...

[trimmed]

...

---->Freeing the memory block: 44 address: 004CC878

Allocating-->block: 45 address: 004D08A8

---->Freeing the memory block: 45 address: 004D08A8

Allocating-->block: 46 address: 004D48D8

---->Freeing the memory block: 46 address: 004D48D8

Allocating-->block: 47 address: 004D8908

---->Freeing the memory block: 47 address: 004D8908

Allocating-->block: 48 address: 004DC938

---->Freeing the memory block: 48 address: 004DC938

...

[trimmed]

...

---->Freeing the memory block: 92 address: 005905A8

Allocating-->block: 93 address: 005945D8

---->Freeing the memory block: 93 address: 005945D8

Allocating-->block: 94 address: 00598608

---->Freeing the memory block: 94 address: 00598608

Allocating-->block: 95 address: 0059C638

---->Freeing the memory block: 95 address: 0059C638

Allocating-->block: 96 address: 005A0668

---->Freeing the memory block: 96 address: 005A0668

Allocating-->block: 97 address: 005A4698

---->Freeing the memory block: 97 address: 005A4698

Allocating-->block: 98 address: 005A86C8

---->Freeing the memory block: 98 address: 005A86C8

Allocating-->block: 99 address: 005AC6F8

---->Freeing the memory block: 99 address: 005AC6F8

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index