malloc - C stdlib.h

C examples for stdlib.h:malloc

Type

function

From


<cstdlib>
<stdlib.h>

Description

Allocate memory block

Prototype

void* malloc (size_t size);

Parameters

Parameter Description
size Size of the memory block in bytes.

Return Value

On success, a pointer to the memory block allocated.

On error, null pointer is returned.

Demo Code


#include <stdio.h>
#include <stdlib.h>

int main ()//  w w w .  j a  va 2 s . c  o  m
{
  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;
}

Related Tutorials