Mattia Paterna Mattia Paterna - 1 year ago 110
C Question

using sizeof(void) inside malloc

I'm a beginner in C and I'm facing this problem: I created a function based on the fast matrix allocation method (Oliveira and Stewart, "Writing Scientific Software", pag. 94) and I want to use it for any data type.
I therefore changed it a bit as follows:

void ** malloc_array2d(size_t m, size_t n){

/* pointer to array of pointers */
void ** pointer;
size_t i;
/* allocate pointer array of length m */
pointer = malloc(m*sizeof(void));
if(pointer == NULL){
return NULL;
/* allocate storage for m*n entries */
pointer[0] = malloc(m*n*sizeof(void));
if (pointer[0] == NULL) {
return NULL;
/* set the pointers */
for (i = 1; i < m; i++) {
pointer[i] = pointer[0] + i*n;

return pointer;

but I get segmentation fault.

The question is: how to allow for memory allocation of different data type, since sizeof(void) is not working (and indeed it returns just 1)?
Any feedback is really appreciated.

Answer Source

void is not the matching type of what pointer references. pointer references void *, not void.

Avoid the mistake in the future by not coding the size of the referenced type, but coding the size of the de-referenced pointer.

// pointer = malloc(m*sizeof(void));
pointer = malloc(sizeof *pointer * m);

For the next allocation, sizeof(void) * m *n is not well defined. Code needs a new approach.

// pointer[0] = malloc(m*n*sizeof(void));

To allocate for various types, pass in the size of the data type.

void ** malloc_array2d(size_t m, size_t n, size_t data_size){
  unsigned char *p = malloc(data_size * m *n);
  for (i = 0; i < m; i++) {
    pointer[i] = p + i*n*data_size;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download