What's the point of malloc(0)?

后端 未结 17 1857
庸人自扰
庸人自扰 2020-11-22 15:40

I just saw this code:

artist = (char *) malloc(0);

...and I was wondering why would one do this?

17条回答
  •  青春惊慌失措
    2020-11-22 15:48

    malloc(0) will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory. Also you can assign values to the memory area but this should be in range with the type of pointer being used. You can also free the allocated memory. I will explain this with an example:

    int *p=NULL;
    p=(int *)malloc(0);
    free(p);
    

    The above code will work fine in a gcc compiler on Linux machine. If you have a 32 bit compiler then you can provide values in the integer range, i.e. -2147483648 to 2147483647. Same applies for characters also. Please note that if type of pointer declared is changed then range of values will change regardless of malloc typecast, i.e.

    unsigned char *p=NULL;
    p =(char *)malloc(0);
    free(p);
    

    p will take a value from 0 to 255 of char since it is declared an unsigned int.

提交回复
热议问题