Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
ciso646 (iso646.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstdlib (stdlib.h)
functions:
abort
abs
atexit
atof
atoi
atol
bsearch
calloc
div
exit
free
getenv
labs
ldiv
malloc
mblen
mbstowcs
mbtowc
qsort
rand
realloc
srand
strtod
strtol
strtoul
system
wcstombs
wctomb
functions (non-standard):
itoa
macros:
EXIT_FAILURE
EXIT_SUCCESS
MB_CUR_MAX
NULL
RAND_MAX
types:
div_t
ldiv_t
size_t


malloc

function
<cstdlib>
void * malloc ( size_t size );

Allocate memory block

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

Parameters

size
Size of the memory block, in bytes.

Return Value

On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* malloc example: string generator*/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
  int i,n;
  char * buffer;
  printf ("How long do you want the string? ");
  scanf ("%d", &i);
  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);
  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';
  printf ("Random string: %s\n",buffer);
  free (buffer);
  return 0;
}


This program generates a string of the length specified by the user and fills it with alphabetic characters. The possible length of this string is only limited by the amount of memory available in the system that malloc can allocate.

See also