0

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.

Community
  • 1
  • 1
Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79
  • this doesn't make sense. why would you return `void **` from a `malloc()` wrapper? And what's wrong with `sizeof`? If you **know** that you **have to** use it for correctness, then why are you not using it? – The Paramagnetic Croissant Apr 27 '14 at 20:09
  • 2
    That book is full of it. `malloc()`, at least nowadays, expects a `size_t` argument, not an `int`. – EOF Apr 27 '14 at 20:10

2 Answers2

1

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.

Daniel
  • 1,920
  • 4
  • 17
  • 35
  • Dude, Thank you very much!, It's been quite a long time since I do not program in C that I was having troubles understanding pointers again. Your answer made me realizes that I was using `ec_malloc` wrong. I only need to call it this way `ec_malloc(sizeof(int) * tam)`. I am feeling now such an idiot for asking this question. – Alejandro Alcalde Apr 27 '14 at 20:16
0

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

par
  • 17,361
  • 4
  • 65
  • 80