Advertisement
tomasaccini

Untitled

Jul 17th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <iostream>
  4.  
  5. class MAL {
  6. public:
  7.     int* a;
  8.     MAL(int valor) {
  9.         a = (int*)malloc(sizeof(int));
  10.         *a = valor;
  11.     }
  12.  
  13.     bool operator == (const MAL& other) {
  14.         return *(this->a) == *(other.a);
  15.     }
  16.  
  17.     MAL& operator = (const MAL& other) {
  18.         if (*this == other) return *this;
  19.         this->a = other.a;
  20.         return *this;
  21.     }
  22.  
  23.     ~MAL() {
  24.         free(a);
  25.     }
  26. };
  27.  
  28. class BIEN {
  29. public:
  30.     int* a;
  31.     BIEN(int valor) {
  32.         a = (int*)malloc(sizeof(int));
  33.         *a = valor;
  34.     }
  35.  
  36.     bool operator == (const BIEN& other) {
  37.         return *(this->a) == *(other.a);
  38.     }
  39.  
  40.     BIEN& operator = (const BIEN& other) {
  41.         if (*this == other) return *this;
  42.         if (this->a) free(this->a);
  43.         this->a = (int*)malloc(sizeof(int));
  44.         memcpy(this->a, other.a, sizeof(int));
  45.         return *this;
  46.     }
  47.  
  48.     ~BIEN() {
  49.         free(a);
  50.     }
  51. };
  52.  
  53. int main() {
  54.     MAL m1(10);
  55.     BIEN b1(10);
  56.     // El siguiente código corriendolo con valgrind nos da un double free.
  57.     // Al salir del scope del if, m2 se destruye, llama a free del atributo a
  58.     // que apunta a la misma direccion de memoria que m1.a. Al salir del scope
  59.     // del main, se llama a free(m1.a), pero esa memoria ya fue liberada.
  60.     /*
  61.     if (true) {
  62.         MAL m2(20);
  63.         m1 = m2;
  64.     }
  65.     */
  66.  
  67.     // el siguiente código es correcto, ya que se hace una copia profunda.
  68.     if (true) {
  69.         BIEN b2(20);
  70.         b1 = b2;
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement