freeing a void pointer

前端 未结 3 573
故里飘歌
故里飘歌 2021-01-28 14:47

How to free a void pointer.

struct vStruct {
    void *vPtr;
    struct vStruct *next;
};

struct vStruct sObj;
struct vStruct *sObjNew = sObj;

delete sObjNew-&         


        
3条回答
  •  一生所求
    2021-01-28 15:23

    How was vPtr initialised?

    • If it points to data the struct doesn't own, you must not destroy it.
    • If it points to data created using malloc, you should call free.
    • If it points to data created using new, you'd need to cast it to the correct (or a compatible) type before calling delete to allow the correct destructor to be called.

    Note that your example code won't compile but suggests vPtr is not being initialised at all. You must initialise vPtr in all vStruct instances you create. Attempting to free an uninitialised vPtr would have undefined consequences but would likely crash.

提交回复
热议问题