Linux内存管理详述(3)

Structure deallocation without free pointers defined in it. When memory is allocated for a strcture, the rentime system will not aytomaticallu allocate memory for any pointers defined within it. Likewise, when the structure goes away, the runtime system will not automatically deallocate memory asigned to the structure’s pointers
The correct way to allocate and deallocate a structure pointer with pointer fields:

void initializePerson(Person *person, sonst char* fn,const char * ln, const chat* title,uint age){ person->firstName=(char*)malloc(strlen(fn)+1); strcpy(person->firstName,fn); ... person->age=age; } void deallocatePerson(Person* person){ free(person->firstName); free(person->lastName); free(person->title); } void processPerson(){ Person* pPerson; pPerson=(Person*)malloc(sizeof(Person)); initilizePerson(pPterson,"Peter","Underwood","Manager",36); ... deallocatePerson(pPerson); free(pPerson); }

Dangling Pointers

a pointer still references the original memory after it has been freed. The use of dangling pointer can result in:

Unpredicatable behavior if the memory is accessed

Segmentation fauts if the memory is no longer accessible

Potential security risks

Several approaches for pointer-induced problem:

Setting a pointer to NULL after freeing it.

Writing special functions to replace the free function.

Some systems(rumtime/debugger) will overwrite data when it is freed

Use third-party tools to detect dangling pointers and other problem

Displaying pointer values can be helpful in debugging dangling pointer

Note:When a pointer is passed to a function, it is always good practice to verify it is not NULL before using it;

2 ways returning a pointer referencing heap

Allocate memory within the function using malloc and return its address. The caller is responsible for deallocating the memory returned;

Pass an object to the function where it is modified.This makes the allocation and deallocation of the object's memory the caller's responsibility.

Several potential problems can occur when returning a pointer from a function:

Return an uninitialized pointer

Returning a pointer to an invalid address

Returning a pointer to a local variable

Returning a pointer but failing to free it =>memory leak

A pointer to one function can be cast to another type.

This should be done carefully since the runtime system doesn’t verify that parameters used by a function pointer are correct.It is also possible to cast a function pointer to a different function pointer and then back. The resulting pointer will be equal to the original pointer, The size of function pointers used are not necessarily the same.
Note that conversion between function pointers and pointers to data is not guaranted to work;

Always make sure you use the correct argument list for function pointers, Failure to do so will result in indeterminate behavior

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/14921.html