不要對C++類對象或struct對象作memset操做

wsrt進程在處理upgradeAccess部分一直Segment fault,又一直沒看出問題。c++

 

http://blog.csdn.net/yasi_xi/article/details/17840225
緣由在於這句修改,前一個版本沒問題,後一個版本必現的話,注意查看版本間相關流程的差別,其實你對比的兩個版本之間只有這一句有差別,你沒仔細看
        CUpgradeAccess cUpgradeAccess;
        //memset(&cUpgradeAccess,sizeof(cUpgradeAccess),0);
        memset(&cUpgradeAccess,0,sizeof(cUpgradeAccess));
post

 

前面的寫法有問題,實際上沒有實質操做。 而這裏原本也不須要實質操做,因此是將錯就錯
後面寫法改對了,產生了實質操做,而後就crash了
 

參考頁面中有下面代碼:ui

 

  1. #include <string.h>   
  2.   
  3. int main() {  
  4.     struct TestStruct  
  5.     {  
  6.         int a;  
  7.         std::string b;  
  8.     };  
  9.   
  10.     TestStruct t = {};  // OK   
  11.   
  12.     {  
  13.         TestStruct t1;  
  14.         memset(&t1, 0, sizeof t1);  // ruins member 'b' of our struct   
  15.     }  // Application crashes here   
  16.       
  17.     return 0;  
  18. }  
#include <string.h>

int main() {
	struct TestStruct
	{
		int a;
		std::string b;
	};

	TestStruct t = {};  // OK

	{
		TestStruct t1;
		memset(&t1, 0, sizeof t1);  // ruins member 'b' of our struct
	}  // Application crashes here
	
	return 0;
}

TestStruct t = {} 是正確的作法,而memset(&t1, 0, sizeof t1) 會致使crash。

 

 

crash的緣由:this

程序在第13行建立 t1 對象,在第15行出了{}做用域的時候,會自動執行 t1 的析構。spa

在析構到 t1 的string成員 b 的時候,由於 b 的內部結構都被 memset 破壞了(都賦成0了),從而不能正常進行析構操做,最終致使crash。.net

 

Crash時的callstack以下:code

 

  1. (gdb) bt  
  2. #0  0x00007f383f9154ab in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() ()  
  3.    from /usr/lib64/libstdc++.so.6  
  4. #1  0x0000000000400810 in TestStruct::~TestStruct (this=0x7fff57c54ee0, __in_chrg=<value optimized out>) at t.cpp:11  
  5. #2  0x0000000000400889 in main () at t.cpp:20  
(gdb) bt
#0  0x00007f383f9154ab in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() ()
   from /usr/lib64/libstdc++.so.6
#1  0x0000000000400810 in TestStruct::~TestStruct (this=0x7fff57c54ee0, __in_chrg=<value optimized out>) at t.cpp:11
#2  0x0000000000400889 in main () at t.cpp:20
相關文章
相關標籤/搜索