Usually a malloc contains sizeof , but this one doesn’t and has i+1 instead:
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);
If you wanted to allocate an array of some type, you would normally multiply the number of elements you wanted by the size of that type, because
malloctakes the size of the array in bytes.However, an array of
charis a special case; you do not need to multiply the number of elements you want bysizeof(char), becausesizeof(char)is defined by the Standard to always be1, and multiplication by 1 yields the other operand.The
+ 1is to make room for theNULterminator. If you want a string of lengthn, your array has to be of lengthn + 1;nspaces for thencharacters of the string, and1space for the terminator.By the way, you shouldn’t cast the return value of
malloc. It will make your code easier to change in the future.