D3m D3m - 1 year ago 94
C Question

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

I have a question about the allocation of memory in the

. I have an int value
. What is the difference between allocating in these ways




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 Source

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))


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download