C++ :Signal: SIGSEGV (Segmentation fault) ,深拷贝

C++ has Signal: SIGSEGV (Segmentation fault) problem when it is running, usually because it accesses the memory space outside the system allocated for this program . As a result, segfaults occur, which often occur when using pointers.

E.g

bounds_ =(int *)malloc(2 * sizeof(int))
bonuds_[0]= 0 ;
bonuns_[1]= 1 ;

base = bound;
cout<<base[0];   // 0 
free(bound);
cout<<base[0];   //Signal: SIGSEGV (Segmentation fault)

Because in base = bound, the address value temp pointed to in bound is assigned to base, and in free (bound), the dynamically allocated memory temo is cast, and then base is used to access temp. A segmentation fault occurred because a memory space other than that allocated by the program was accessed.

The direct assignment between the above base = bound pointers is a shallow copy, and the two pointer variables point to the same memory space. The deep copy is to re-allocate the memory space to the new pointer variable when assigning.

The above code can be changed to:

bounds_ =(int *)malloc(2 * sizeof(int));
bonuds_[0]= 0 ;
bonuns_[1]= 1 ;

base =(int *)malloc(2 * sizeof(int));
for (i =0 ; i< 2 ;i++){
   base[i]=bound_[i];
}

cout<<base[0];   // 0 
free(bound_);
cout<<base[0];   //0

The advantage of deep copy is that the two pointers do not affect each other, and the copied points point to the contents of the memory instead of the address value in the pointer variable.

The shallow copy problem mainly occurs in the part of memory reclamation. C++ generally does not reclaim dynamically allocated memory.

In C, malloc is used to allocate memory, and free is used to manually release memory. C++ uses new to allocate memory and delete to manually release memory.

In C++, there is a standard library called the Boost library. When   boost::shared_ptr is  used to manage the new memory, it does not need to be manually cast. It will automatically use useless dynamically allocated memory. By reference counting the allocated memory, if the allocated memory reference count reaches 0, that is, when the program has no variables that can point to this memory, it will be automatically released. For deep copy of pointers, please refer to:

https://blog.csdn.net/superSmart_Dong/article/details/108178633

Guess you like

Origin blog.csdn.net/superSmart_Dong/article/details/108067987