0

what is the difference between these two malloc functions?

char *s; //declaration

--> s = malloc(1024 * sizeof(char));

--> s=(char *)malloc(1024*sizeof(char));

Do here too, we need to typecast the malloc function if it is already declared in char

Gautam Goyal
  • 230
  • 1
  • 4
  • 16
  • 2
    Does this answer your question? [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ackdari Apr 09 '20 at 13:05
  • You never cast the return value of malloc, so the first version is correct. On an unrelated note, there's an alternative syntax you can use to specify the size: sizeof(char[1024]). Doesn't have anything to do with malloc, just a little syntactic sugar which i personally rather like – Felix G Apr 09 '20 at 13:09
  • 2
    `malloc()` returns a `void*` which is implicitly converted into `int*` in C, so it doesn't make any difference and therefore the second line is redundant and does nothing more than making the code harder to read. Unrelated, but, this is different in case of C++ where you need to actually cast the result of `malloc()` because C++ doesn't allow implicit conversion of `void*` to `int*`. – Ruks Apr 09 '20 at 13:25
  • 1
    @FelixG: I like that syntax too, but if the size is not a compile-time constant, it only works with compilers which implement variable length arrays (VLAs). VLAs are an optional feature in the current C standard thanks to lobbying from a vendor who apparently has no interest in implementing the feature. – rici Apr 09 '20 at 13:26

1 Answers1

0

The second case is not preferred, the cast is not needed. Use the first syntax.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261