The following code compiles, but delivers an error at runtime:
# 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" ;
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 ;
}
It outputs something like:
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
I do not understand why he says:
0x10f9bcf64: pointer freed
since it b.nameis obviously aimed at 0x10f9bcf64and no longer overlaps with a!
I am also wondering how to solve this problem? Thank!
source
share