mardi 22 mai 2018

Cpp program not exiting in cygwin when free is missing

I wrote a small cpp file to illustrate something to a friend, and noticed curious behaviour: The program does not exit or react to CTRL+C after the second print when run in cygwin, but works as expected when run from the powershell or recompiled&run on linux.
When I uncomment the line //free(map);, the program exits normally.

I would like to know why cygwin freezes, so that I have to close the mintty window - and if it is an issue with my machine, how to fix it.

#include<iostream> // for std::cout
#include<cstdlib> // for atoi, uses input 0 for invalid numbers
#include<stdio.h> // for printf

// typedef for clearer code
typedef int matrixcontent; // change 'int' to whatever kind of elements there are in the matrix

// declarations first, so I can write main whereever I want to
void printMatrix(matrixcontent* map, size_t dimX, size_t dimY) ;
void fillMatrix(matrixcontent* map, size_t dimX, size_t dimY) ;

int main(int argc, char** argv){
    if(argc!=3){
        printf("%s", "please give exactly two arguments.");
        return 1;
    }

    // arg to int
    int y = atoi(argv[1]);
    int x = atoi(argv[2]);

    // create matrix
        // allocate memory space
        matrixcontent* map = (matrixcontent*) malloc(sizeof(matrixcontent)*x*y);
        if(map==NULL){
            printf("%s", "Not enough memory");
        }

    // print current (random) content
    printMatrix(map, x, y);
    // fill matrix
    fillMatrix(map, x, y);
    // print the modified matrix again
    printMatrix(map, x, y);

    //free(map);
    return 0;
}

void printMatrix(matrixcontent* map, size_t dimX, size_t dimY) {
    for(size_t row=0; row<dimY; row++){
        for(size_t col=0; col<dimX; col++){
            std::cout << map[row*dimY+col] << ",\t";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl << std::endl;
}

void fillMatrix(matrixcontent* map, size_t dimX, size_t dimY) {
    for(size_t row=0; row<dimY; row++){
        for(size_t col=0; col<dimX; col++){
            map[row*dimY+col] = col+row; // fill with something
        }
    }
}

I compiled it with g++ --std=c++11 -Wall -Wextra -O0 -g example.cpp -o example in cygwin x64.

I consider this question on-topic because

Aucun commentaire:

Enregistrer un commentaire