What's the point of malloc(0)?

后端 未结 17 1778
庸人自扰
庸人自扰 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:50

    malloc(0) will return NULL or a valid pointer which can be rightly passed to free. And though it seems like the memory that it points to is useless or it can't be written to or read from, that is not always true. :)

    int *i = malloc(0);
    *i = 100;
    printf("%d", *i);
    

    We expect a segmentation fault here, but surprisingly, this prints 100! It is because malloc actually asks for a huge chunk of memory when we call malloc for the first time. Every call to malloc after that, uses memory from that big chunk. Only after that huge chunk is over, new memory is asked for.

    Use of malloc(0): if you are in a situation where you want subsequent malloc calls to be faster, calling malloc(0) should do it for you (except for edge cases).

提交回复
热议问题