Home > Net >  Problems to understand the size of malloc parameter
Problems to understand the size of malloc parameter

Time:11-03

Can anyone explain how does below code work? Cuz I found myself don't know what |malloc(inputNim 1)andexit(1)` stands for in below code...

buffer = (char*) malloc (inputNum 1);
if (buffer==NULL) exit (1);

CodePudding user response:

This line tries to allocate inputNum 1 bytes of memory:

buffer = (char*) malloc (inputNum 1);

The below line checks if the above allocation succeeded. If malloc fails, it returns nullptr (NULL) and the decision is then to exit the program with return value 1. A common convention is to exit with 0 on success and something else on failure.

if (buffer==NULL) exit (1); // if allocation failed, end program
  • Related