"HEAP CORRUPTION DETECTED"

Asked

Viewed 190 times

1

Can anyone help me out here? Destructor problem.

(UP) I think I found the problem, I will comment on the code:

If anyone can give me some tips on good practice in this code, please!

Kript::Kript(const char* novoTexto)
{
    texto_size = strlen(novoTexto); // * essa linha mudei para (strlen(novoTexto)+1)*
    texto = (char*) malloc(sizeof(char)*texto_size);
    strcpy(texto, novoTexto);       // *pois aqui strcpy copia novoTexto + '\0'*
    kripted_txt = (int*)malloc(sizeof(int)*texto_size);
    Enkrip();
}



void Kript::Enkrip()
{
    file = fopen("KRIPTED.txt", "w");
    if (file == NULL)
    {
        std::cout << "ERRO AO ABRIR ARQUIVO";
    }
    else
    {
        int* EOF_POINT = kripted_txt;
        for (int i = 0, j = 0; i < texto_size; i++, j = 0)
        {
            if (j > KEY_SIZE)
                j = 0;
            kripted_txt[i] = texto[i] * key[j];
            EOF_POINT++;
        }
         EOF_POINT--;      //<- adicionado, pois EOF estava sendo adicionado...
                           //...Fora do espaco alocado

        *EOF_POINT = EOF;  // agora sim
        EOF_POINT = kripted_txt;

        while (*EOF_POINT != EOF)
        {
            fprintf(file, "%d", *EOF_POINT);
            EOF_POINT++;
            if (*EOF_POINT != EOF)
                fprintf(file, " ");

        }



    }

}

Kript::~Kript()
{
   free(texto);   
   free(kripted_txt); 
   fclose(file);
}
  • Your code is C++ but you still use malloc and char*? Why not use streams and strings to solve the problem?

  • You’re right, alias already changed from malloc and free, to new and delete, but I haven’t practiced the use of Std::string,

1 answer

0


Your code has few elements of c++ it is practically using only c. You should try to replace the use of the arrays with Std::string and also use the class for handling fstream header files. This will already make your code clearer and with a lower chance of errors.

A modification that would already help a little, for example, serious change the constructor to the following

#include<string>

Kript::Kript(const std::string & novoTexto)
     :texto(novoTexto)
{
      Enkrip();
} 

Using Std::string you will not need to worry about memory allocation at all times and you will also not need to keep saving the size of the string, because Std::string knows its own size by the size() method. Take a look at reference c/c++ you were probably able to make the modifications and the problem of your code had disappeared.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.