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

后端 未结 4 676
梦如初夏
梦如初夏 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条回答
  •  梦毁少年i
    2020-12-30 01:51

    These statements are not using malloc on newPtr.

    The statement newPtr = malloc(10 * sizeof(int)); cause these operations:

    1. sizeof(int) is evaluated.
    2. That value is multiplied by 10.
    3. malloc is called, and that product is passed to it.
    4. malloc returns a value.
    5. That value is assigned to newPtr.

    So you see, at step 3, newPtr is not involved in any way. Only after malloc is done is newPtr involved.

    When you call malloc a second time, it has no way of knowing you are doing anything with newPtr. It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr, which erases the old value that was in newPtr.

    At that point, you have no way of knowing what the old value was. The space is still allocated, because it was not freed, but you do not have a pointer to it.

提交回复
热议问题