Search code examples
arrayscmemorymalloc

Is malloc(sizeof(char[length])) incorrect?


When I dynamically allocate an array in C++, I use the following:

char* arr = new char[length];

So naturally, when I started learning C, I have been using the following to allocate my strings:

char* arr = malloc(sizeof(char[length]));

However, I see that common practice is to use the following instead:

char* arr = malloc(length * sizeof(char));

Are the statements above equivalent, or is there some reason I should not use sizeof(char[length])?


Solution

  • The two are effectively the same.

    sizeof(char[length]) evaluates to the size in bytes of an array of char of length length. This is the same value as length * sizeof(char).

    While the latter is more common, the former is fine as well. The only caveat is that some compilers, i.e. MSVC, don't support variable length arrays in which case sizeof(char[length]) would be invalid.