我试图避免在我的代码中发生内存泄漏。我需要取消分配pElement,line和pSecond,而不会丢失pImage中的值。因为我需要在打印功能中打印这些值。如何释放我需要的结构指针
我的add函数包含struct GraphicElement * pElements; struct GraphicElement * pSecond ;, struct Point point ;.
我使用malloc为每个结构分配内存,然后添加值,然后将最终值传递给pImage。除了最终导致3个内存泄漏的事实之外,我所有其他的函数都能正常工作。因为我没有免费(pSecond); .... free(pElement)... free(line);
如果我试图在我的函数退出之前释放它们并将值传递给pImage之后。我的价值观都被抹去了。
如何在本地添加函数中释放这些值?
struct Point
{
int x, y;
};
struct Line
{
Point start;
Point end;
};
struct GraphicElement
{
enum{ SIZE = 256 };
unsigned int numLines; //number of lines
Line* pLines; //plines points to start and end
char name[SIZE];
};
typedef struct
{
unsigned int numGraphicElements;
GraphicElement* pElements; //the head points to pLines
} VectorGraphic;
void InitVectorGraphic(VectorGraphic*); //initializes pImage->pElement
void AddGraphicElement(VectorGraphic*); //Used to add
void ReportVectorGraphic(VectorGraphic*); // prints pImage contents
void CleanUpVectorGraphic(VectorGraphic*); //deallocates memory
听起来像你的pImage正在使用这些值。为什么他们需要在你的添加中被释放?为什么不在“CleanUpVectorGraphic”函数中释放它们? – NullEntity
如果你需要一个结构指针,那么你为什么要首先释放它呢?国际海事组织,你应该解释你想做什么,因为我不明白你想要达到什么。 –
@Disillusioned是否可以从另一个函数访问这些结构?我知道我可以免费(pImage);和它的所有内容在一个循环中。但是线,pSecond和pElement如何。我如何从清理功能访问它们? – Calidreaminn