Reputation: 1356
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) {
free(pointer);
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. Thanks.
Upvotes: 0
Views: 2864
Reputation: 237
Firstly the value of the sizeof(void) is always 1, here void refers to pointer memory allocation for untyped datatype. I don't think any other datatype takes that much less memory. Well int, float, etc consumes more bit of data. If you want the value of sizeof() to return 1, You can just manually specify the size in malloc() function instead of using sizeof() functionalities along with different datatypes.
Upvotes: -1
Reputation: 347
Sizeof returns the quantity of bytes that every datatype are. 1 for byte, 2 for int16, 4 for int32, etc... You can then pass it as parameter, with any kind of problem, as at the moment of use of malloc_2darray function you should know final datatype to map to.
Note that always you use your malloc_2darray function you should cast to final datatype pointer for a correct interpretation of returned pointers.
Upvotes: 0
Reputation: 154592
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;
}
Upvotes: 2