下面的代碼編譯,但在運行時提供了一個錯誤的連續內存塊:析構函數是無法刪除已分配
# include <iostream>
# include <string.h>
class A {
public:
A() {}
A (int id, char * t_name) {
_id = id ;
name = new char [ strlen (t_name) + 1 ] ;
strcpy (name, t_name) ;
}
char *name ;
int _id ;
~A() { delete [] name ;}
} ;
int main() {
A a (1, "123") ;
A b ;
b = a ;
std::cout << static_cast < const void * > (a.name) << std::endl ;
std::cout << static_cast < const void * > (b.name) << std::endl ;
b.name = "abc" ; // b.name is directed to a different memory block
std::cout << static_cast < const void * > (a.name) << std::endl ;
std::cout << static_cast < const void * > (b.name) << std::endl ;
std::cout << a.name << std::endl ;
std::cout << b.name << std::endl ;
return 0 ;
}
它輸出類似:
0x7ff87bc03200
0x7ff87bc03200
0x7ff87bc03200
0x10f9bcf64
123
abc
a.out(883,0x7fff7ee3d000) malloc: *** error for object 0x10f9bcf64:
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
我不明白它爲什麼說:
0x10f9bcf64:被釋放的指針未被分配
因爲b.name
顯然是針對0x10f9bcf64
,並且不再與a
重疊!
我也想知道如何解決這個問題?謝謝 !
規則的精彩世界你已經違反了法則三。 –
'b.name'不是'new''d內存,所以它不能'delete'd –