Loop End Error (Bug delete with char *)

-3

1 - I have this code (I gave a summary, type -1, and then 'n' to exit the loop and the error occurred):

#include <iostream>
#include <cstdlib>
#include <cstdio>
#undef max
using namespace std;

int* cont = new int(0);

//-----------------------------------------// MAIN // -----------------------------------//

void main(){
    char* n = new char('s');

    while (*n == 's' || *n == 'S'){

        int* dinheiro = new int(500);

        while (*dinheiro >= 1){
            printf("Quanto Deseja Apostar ? ");
            scanf("%d%*c", &*dinheiro);

            printf("\nTentar Novamente (s-n) ? ");
            cin >> n;
            cin.ignore(numeric_limits<int>::max(), '\n');
            system("cls");

        }
        delete dinheiro;
    }
    delete n;
}

And in that part:

printf("Tentar Novamente (s-n) ? ");
cin >> *n;
cin.ignore(numeric_limits<int>::max(), '\n');
system("cls");

If the user does not type 's' to go back in the loop he gives this error:

Note: Removing the delete program works correctly.

    
asked by anonymous 13.12.2014 / 23:28

1 answer

4

See the line:

cin >> n;

The variable n is char *, so the > > thinks there is an array allocated there, and reads things that do not fit in the buffer ("-1" has 2 chars). Neither is there a buffer, because you have dynamically allocated only 1 char (to train, OK, in a real program, it seems without purpose).

I suggest that you then change to:

cin >> *n;

or

scanf("%c", n);

If you type -1, the line above (any one) will read only the "-", without saving outside the allocated space.

Another thing: &*dinheiro is kind of useless. The & and * are canceled (in the absence of operator overloading), and would be the same as writing only dinheiro .

And an important lesson in the world of C and C ++: the fact that the compiler accepts is very loosely related to the fact that the program is correct.

    
14.12.2014 / 01:08