Is there something wrong with using sizeof (type [1234])?

I have been using it for many years, that is:

text = (char *)malloc( sizeof(char[1234]) );

instead:

text = (char *)malloc( sizeof(char) * 1234 );

People told me that it was dangerous, but no one could say why. I checked the C specification and became legal. Are there any pitfalls here?

+3
source share
5 answers

This may be legal, but there are a few pitfalls.

First, if you (or the maintainer later) blindly replace the type with an expression, you will have problems:

sizeof(char *) * 4 => sizeof(x) * 4  // OK
sizeof(char *[4])  => sizeof(x[4])   // NOT OK

Secondly, not all compilers can support variable length arrays:

sizeof(char *) * n  // ALWAYS SUPPORTED
sizeof(char *[n])   // MAY NOT BE SUPPORTED

Finally, this is not a very common idiom, so people reading the code can be confused for a moment.

, , , :)

+7

, , :

someptr = malloc(number_elems * sizeof *someptr);

, malloc, .

int *data;
data = malloc(100 * sizeof *data);

... , unsigned long...

unsigned long *data;
data = malloc(100 * sizeof *data); /* no change from previous version */
+4

, , :

text = (char *)malloc( sizeof(char[1234]) );

sizeof , , , .

, , , - , .

. C99 , .

, C.

+3

:

text = malloc(sizeof(*text)*1234));

, , i18n :

char *text;

:
wchar_t *text;

1234 , , 'char' 'wchar_t' . , - short vs. int vs. long, float vs. double ..

+3

. . .

,

size_t x = sizeof(double[99]);
size_t y = sizeof(double)*99;

,

void fun(int i) {
    size_t x = sizeof(double[i]);  // error, no compile-time constant
    size_t y = sizeof(double) * i; // Fine
}
0

Source: https://habr.com/ru/post/1718662/


All Articles