Home > Software design >  Role of sizeof in malloc
Role of sizeof in malloc

Time:08-20

My allocation works partially. However I dont understand the use of sizeof(). Also *num, I thought the correct use would be (unsigned short*)num

I get some errors if I dont use it, but why is it supposed to be used.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

unsigned short *reverse_seq(unsigned short num) {
    if (num == 0) return NULL;
    unsigned short *ret = malloc((unsigned short)num);             //Works partially
    //unsigned short *ret = malloc(sizeof(unsigned short)*num);    //Correct allocation
    for (int i = 0; i < num; i  )
        ret[i] = num - i;
    return ret;
}

int main() {
    unsigned short *ret = reverse_seq(4u);
    for (unsigned short i = 0; i < 4;   i)
        printf("%u", ret[i]);
 }

CodePudding user response:

The parameter to malloc is the number of bytes to allocate. You are trying to return an array of unsigned short with num elements. To get the correct size, you need to multiply the size of a single element sizeof(unsigned short) by the number of elements num. Your correctly working statement does exactly that; the * is not a dereference but a multiplication.

  • Related