2

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);
Caffeinated
  • 11,982
  • 40
  • 122
  • 216

3 Answers3

14

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 malloc takes the size of the array in bytes.

However, an array of char is a special case; you do not need to multiply the number of elements you want by sizeof(char), because sizeof(char) is defined by the Standard to always be 1, and multiplication by 1 yields the other operand.

The + 1 is to make room for the NUL terminator. If you want a string of length n, your array has to be of length n + 1; n spaces for the n characters of the string, and 1 space 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.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
3

C strings are null-terminated, see:

E.g. "abc" is represented as "abc" + NUL. Thus, for a string of length i, you need to allocate i + 1. As you are allocating chars, sizeof(char) is 1, so you actually need to allocate 1 * (i + 1), but that's the same.

icyrock.com
  • 27,952
  • 4
  • 66
  • 85
2

If its allocating for a string you need enough memory for the number of characters + 1 extra for the null character that denotes the end of the string (\0)

jrbalsano
  • 834
  • 7
  • 18