Let's start from a demonstrative program.
Here you are.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
size_t n = 14;
char *s = malloc( n );
if ( s != NULL )
{
strcpy( s, "Hello World!" );
puts( s );
}
free( s );
return 0;
}
The program output is
Hello World!
So in this declaration
char *s = malloc( n );
there was allocated enough memory to store the string literal "Hello World!"
. However the system can have no enough memory. In this case the returned by the function malloc value of the pointer will be equal to NULL.
So before using the allocated memory we are checking whether the memory was allocated successfully.
if ( s != NULL )
If so then we may copy the string literal "Hello World!"
to the allocated memory.
strcpy( s, "Hello World!" );
Usually beginners make an error. Instead of coping a string literal (or some other string) in the allocated memory they just write
s = "Hello World!";
After this assignment the address of the allocated memory is lost and the pointer s
points now to the memory occupied by the string literal instead of the allocated memory. As a result there is a memory leak.
When we not need the object stored in the allocated memory the memory must be freed.
free( s );
That is all at the first time.
In general when you are allocating a memory for an array of N
elements that have the type T
(where T
is an arbitrary type) then you need to write
T *p = malloc( N * sizeof( T ) );
For example if you want to allocate an array of 10 integers you should write
int *p = malloc( 10 * sizeof( int ) );
sizeof( char )
is always equal to 1
. So in the demonstrative program above I wrote
char *s = malloc( n );
because it is the same as
char *s = malloc( n * sizeof( char ) );
Also in C it is unnecessary to cast the returned value of malloc like
T *p = ( T * )malloc( N * sizeof( T ) );
because the function malloc
returns a pointer of the type void *
that can be implicitly converted to pointer to object of any other type. You can use casting for self-documenting your code.
Opposite to C in C++ there is no such implicit conversion. So in C++ you have to use casting
T *p = ( T * )malloc( N * sizeof( T ) );