Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])?

like image 820
JeremyEastham Avatar asked Aug 30 '25 16:08

JeremyEastham


1 Answers

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.

like image 108
dbush Avatar answered Sep 02 '25 05:09

dbush