What happens if I use malloc twice on the same pointer (C)?

后端 未结 4 674
梦如初夏
梦如初夏 2020-12-30 01:31

Say for instance I created a pointer newPtr and I use malloc(some size) and then later I use malloc(some size) again with the same pointer. What happens? Am i then creating

4条回答
  •  [愿得一人]
    2020-12-30 02:04

    You're not "using malloc on the same pointer". You're calling malloc() (which allocates space and returns a pointer to that space) and assigning its returned value to the same pointer object. (malloc itself has no idea what you're going to do with the result it returns.)

    The second assignment, as with any assignment, will replace the previously stored value.

    Which means that, unless you saved it elsewhere, you no longer have a pointer to the first allocated chunk of memory. This is a memory leak.

    In addition, you should always check whether the result returned by malloc is a null pointer, and if so, take some corrective action. In the simplest case, that might be just printing an error message and terminating the program. You definitely should not assume the malloc call succeeded and then try to use the (nonexistent) allocated memory. (This isn't relevant to your question, but it's something that's easily missed, especially since allocation failures are rare in most contexts.)

提交回复
热议问题