behaviour of malloc(0)

后端 未结 3 2065
旧巷少年郎
旧巷少年郎 2020-11-30 13:48
int main()
{
    char *p;
    p = (char* ) malloc(sizeof(char) * 0);
    printf(\"Hello Enter the data without spaces :\\n\");
    scanf(\"%s\",p);
    printf(\"The          


        
3条回答
  •  失恋的感觉
    2020-11-30 14:35

    It is implementation defined what malloc() will return but it is undefined behavior to use that pointer. And Undefined behavior means that anything can happen literally from program working without glitch to a crash, all safe bets are off.

    C99 Standard:

    7.22.3 Memory management functions
    Para 1:

    If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

提交回复
热议问题