Introduction to Programming and C++

Contents Previous Topic Next Topic

In C++, memory is dynamically allocated using the two operators new and new[]. It is deallocated using the corresponding delete or delete[], respectively.

In C, there is a one function which allows you to request memory from the operating system: malloc( int ) which stands for memory allocate. This is a function which takes a single argument: how many bytes you require. It returns a void * pointer, that is, a pointer which could point to anything.

To deallocate memory, simply pass the returned pointer to the free function: free( void * ).

Program 1 demonstrates how you can request and return memory for a double (which uses 8 bytes). Like new and delete, each time you call malloc, you should also plan to call free, otherwise, you may experience a memory leak.

Program 1. Simple memory allocation.

#include <stdio.h>

int main() {
	double * x = malloc( 8 );

	*x = 3.1415;

	printf( "An approximation of pi is %lf\n", *x );

	free( x );

	return 0;
}

There is a significant problem with the request in Program 1, namely, you must know exactly how much memory you want. According the the IEEE 754 specification, the double must be eight bytes, but the size of an int will change from platform to platform. We can solve this with the sizeof operator. Program 2 demonstrates this by improving the code shown in Program 1.

Program 2. Intelligent memory allocation.

#include <stdio.h>

int main() {
	double * x = malloc( sizeof( double ) );

	*x = 3.1415;

	printf( "An approximation of pi is %lf\n", *x );

	free( x );

	return 0;
}

If you want to allocate memory for an array, you simply ask for as many entries in the array multiplied by the size of the object you're asking for. For example, Program 3 demonstrates dynamic array memory allocation for an array of 1015 doubles, assigns to each entry, sums the results, and then frees the memory.

Program 3. Allocating memory for an array.

#include <stdio.h>

int main() {
	int array_size = 1015;

	double * x = malloc( array_size * sizeof( double ) );

	int i;   /* must be declared here */

	for ( i = 0; i < array_size; ++i ) {
		x[i] = 1.0 / ( i + 1.0 );
	}

	double sum = 0.0;

	for ( i = 0; i < array_size; ++i ) {
		sum += x[i];
	}

	printf( "The sum of the reciprocals from 1 to %d is %lf\n",
		array_size, sum );

	free( x );

	return 0;
}

Comment About sizeof

You may wonder how sizeof works. When you call sizeof, the result is actually calculated by the compiler and not at run-time. Thus, all calls to sizeof are actually calculated at compile time.


Questions

1. Write a program which prints the size of each of the built-in data types in C. (Note, bool is not a built-in data type.)


Contents Previous Topic Top Next Topic