Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <string.h>
- #include <iostream>
- class MAL {
- public:
- int* a;
- MAL(int valor) {
- a = (int*)malloc(sizeof(int));
- *a = valor;
- }
- bool operator == (const MAL& other) {
- return *(this->a) == *(other.a);
- }
- MAL& operator = (const MAL& other) {
- if (*this == other) return *this;
- this->a = other.a;
- return *this;
- }
- ~MAL() {
- free(a);
- }
- };
- class BIEN {
- public:
- int* a;
- BIEN(int valor) {
- a = (int*)malloc(sizeof(int));
- *a = valor;
- }
- bool operator == (const BIEN& other) {
- return *(this->a) == *(other.a);
- }
- BIEN& operator = (const BIEN& other) {
- if (*this == other) return *this;
- if (this->a) free(this->a);
- this->a = (int*)malloc(sizeof(int));
- memcpy(this->a, other.a, sizeof(int));
- return *this;
- }
- ~BIEN() {
- free(a);
- }
- };
- int main() {
- MAL m1(10);
- BIEN b1(10);
- // El siguiente código corriendolo con valgrind nos da un double free.
- // Al salir del scope del if, m2 se destruye, llama a free del atributo a
- // que apunta a la misma direccion de memoria que m1.a. Al salir del scope
- // del main, se llama a free(m1.a), pero esa memoria ya fue liberada.
- /*
- if (true) {
- MAL m2(20);
- m1 = m2;
- }
- */
- // el siguiente código es correcto, ya que se hace una copia profunda.
- if (true) {
- BIEN b2(20);
- b1 = b2;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement