D3m D3m - 2 months ago 9
C Question

C - computing sum and multiply it by sizeof in malloc()

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?

Answer

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
Comments