Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

The malloc function (and your ec_malloc) both allocate a linear region of bytes that is size bytes long.

sizeof simply returns an int and it isn't related to malloc in any way (other than it is frequently used with malloc).

A 32-bit integer is 4 bytes long. sizeof(int) returns 4. If you want space for 4 ints, you would say malloc( sizeof(int) * 4 ).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top