Friday, 13 May 2016

c - The use of sizeof in malloc



I am trying to wrap the creation of a matrix into a function, but I am having problems trying to understand the following code snippet extracted from a book:




  // An error checked malloc() wrapper function
void *ec_malloc(unsigned int size) {
void *ptr;
ptr = malloc(size);
if(ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}



I've already check this question:



Do I cast the result of malloc?



And now I now it is not necessary to cast the result. But what I don't understand is the use of malloc(size) without a sizeof operator. For example, to create a matrix, lets say int **matrix I've also created this function:



  // An error checked malloc() wrapper function
void **double_ec_malloc(unsigned int size) {
void **ptr;

ptr = malloc(size);
if(ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}


And then I do:



  int **matrixA = double_ec_malloc(size);


int i = 0;
for (i = 0; i < size; i++){
matrixA[i] = ec_malloc(size);


The man of malloc says:




The malloc() function allocates size bytes and returns a pointer to the allocated memory.





Let size be 4, then in ptr = malloc(size) I am allocating 4 bytes, but if matrix is of type int. Wouldn't I need sizeof int * 4? Because right now I think I am not allocating enough memory for an integer matrix.


Answer



Since ec_malloc() doesn't take a datatype argument, it assumes you will do sizeof(datatype) * size yourself. Thus the argument unsigned int size should be in bytes.



Notice how that it is exactly how malloc() itself behaves.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...