1

It's been a white since I've written for Microcontrollers, and I'm trying to refactor some code to work on such a device, in C.

I have a line of code:

Pieces = calloc(ARRAYSIZE, sizeof(struct piece));

http://www.cplusplus.com states that calloc:

Allocates a block of memory for an array of num elements, each of them size bytes long

Would the equivalent malloc operation then be:

Pieces = Malloc(ARRAYSIZE*sizeof(struct piece));

Disregarding that the bits haven't been set to 0, isn't that about the same? Or would I have to allocate a block of memory for ARRAYSIZE times?

Hope you can help.

Benjamin Larsen
  • 560
  • 1
  • 7
  • 21
  • Yes, malloc accepts a single argument which is size in bytes (did you mean stdlib's `malloc`?) – bipll Jan 02 '18 at 17:11
  • Yes - what you have is equivalent as far as allocation is concerned. But there are subtle differences (which may or may not matter to your use-cases). See: https://stackoverflow.com/q/1538420/1275169 – P.P Jan 02 '18 at 17:11
  • `ARRAYSIZE*sizeof(struct piece)` may result in an undetectable overflow. `calloc(ARRAYSIZE, sizeof(struct piece))` can detect a too large a product. – chux - Reinstate Monica Jan 02 '18 at 17:15
  • See also https://stackoverflow.com/questions/8752546/how-does-malloc-understand-alignment – Paul Ogilvie Jan 02 '18 at 17:16

1 Answers1

2

The things that make calloc(x,y) different from malloc(x*y) are the facts that (1) the size of the former allocation is the arithmetical product of x and y, even if that value would exceed SIZE_MAX [typically an implementation would return a null pointer for such an allocation request, but if an implementation can somehow satisfy the request, the Standard would allow it to do so]; (2) the storage will be cleared and may be read, without UB, as any type where all-bits-zero is a legitimate value [on most platforms all types would qualify, but the Standard would allow all-bits-zero to be a trap value for pointers or floating point types].

supercat
  • 77,689
  • 9
  • 166
  • 211
  • Should `x*y` exceed `SIZE_MAX`, `malloc(x*y)` may be easy to satisfy as the product (after overflow) could be quite small. Of course the memory then allocated is too small. – chux - Reinstate Monica Jan 02 '18 at 17:18
  • 1
    @chux: That's one of the behavioral differences I noted between malloc(x*y) and calloc(x,y). I've long been irked by the fact that the Standard Library tends to group what should be independent aspects of functionality, like whether an allocation should be scaled and whether it should guarantee the memory is cleared, or--as some other unwelcome pairings, whether a function receiving a line of input should strip out a newline and whether to allow the caller to set a maximum length, or whether a function should output a string to the console versus something else and whether to add a newline. – supercat Jan 02 '18 at 19:33