简体   繁体   中英

C++ delete storage space in a different function from where it was allocated

Will I get undefined behavior if I delete a storage space in a different function from where the space was originally allocated?

typedef struct {
    unsigned int Data1;
    unsigned int Data2;
    unsigned int Data3;
}TData;

void CreateStorage(void)
{
    TData *TempData = new TData;

    DeleteStorage((unsigned char*)TempData); 
}

void DeleteStorage(unsigned char *StorageToDelete)
{
    delete (TData*)StorageToDelete;
}

从不同功能分配和删除内存是完全有效的。

No.

[ Note: you don't need that cast. ]

As long as you're allocating and deallocating within the same library, it will be deleted safely.

However, there are things to note if you are allocating and deallocating in different libraries. Since the underlying class definition may be different amongst different libraries, you need to make sure that you're using the same definition.

One very common problem that arises is when you're using a precompiled open source C++ library and your program and the library use different C++ runtime library, it will sometimes crash while the open source library deallocates a STL container instance that has been allocated by your program because the definition of that class in the open source library is different from yours. The common workaround in solving this problem is to recompile the open source library using the compiler that you use.

No, it's ok. Why do you cast StorageToDelete to (TData*) in DeleteStorage()?

No, that's fine, and also don't typedef your structs. Just say struct TData { /*...*/ }; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM