1

I have a question about the allocation of memory in the malloc(). I have an int value k. What is the difference between allocating in these ways

...=(int*)malloc(k*sizeof(int));

and

...=(int*)malloc(((2*k-1)-k+1)*sizeof(int));

knowing that (2*k-1)-k+1) == k?

The result of both is the same or in the second case, even if ((2*k-1)-k+1) == k, can change something?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
D3m
  • 23
  • 1
  • 6
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). โ€“ Sourav Ghosh Sep 19 '16 at 17:42

2 Answers2

0

First of all, please see this discussion on why not to cast the return value of malloc() and family in C..

That said, malloc() takes the argument for the number of bytes of memory to be allocated.

Quoting C11, chapter ยง7.22.3.4, The malloc() function

void *malloc(size_t size);

The malloc function allocates space for an object whose size is specified by size [...]

So, as long as x and y evaluates to same value,

malloc(x * sizeof(sometype))

and

malloc(y * sizeof(sometype))

will give you pointers with same amount of memory to be accessed, provided the calls are success.

Finally, it's always better approach to not to use hardcoded values for the sizeof operator, rather use the variable itself. Makes the code more robust, like

  int *p = NULL;
  .
  .
  .
  p = malloc (x * sizeof(*p));  // type of `p` can change, 
                                // this statement need not be changed
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Although mathematically equivalent to k, the product (2*k-1)-k+1 may overflow resulting in undefined behavior. A difference for half of the int range versus using k.

... = malloc(((2*k-1)-k+1)*sizeof(int))

k*sizeof(int) product itself make overflow, but the product is well-defined, even if not desirable.

The possibility of overflow depends on the range of size_t vs. int. size_t is typically twice the positive range of int and perhaps many times more. Rarely is it less. Recommend:

int *p = malloc(sizeof *p * k);

Notes:

  1. Casting the result of malloc() is not needed.
  2. Using sizeof *p rather than sizeof(int) is less likely to mis-code, easier to review and maintain.
  3. Having sizeof *p first insures much of the following math to occur using at least size_t math.
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256