What happens to memory after '\0' in a C string?

前端 未结 11 1739
难免孤独
难免孤独 2020-12-23 11:25

Surprisingly simple/stupid/basic question, but I have no idea: Suppose I want to return the user of my function a C-string, whose length I do not know at the beginning of th

11条回答
  •  清酒与你
    2020-12-23 11:54

    malloc just allocates a chunk of memory .. Its upto you to use however you want and call free from the initial pointer position... Inserting '\0' in the middle has no consequence...

    To be specific malloc doesnt know what type of memory you want (It returns onle a void pointer) ..

    Let us assume you wish to allocate 10 bytes of memory starting 0x10 to 0x19 ..

    char * ptr = (char *)malloc(sizeof(char) * 10);
    

    Inserting a null at 5th position (0x14) does not free the memory 0x15 onwards...

    However a free from 0x10 frees the entire chunk of 10 bytes..

提交回复
热议问题