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