Search code examples
cvariablesmemoryansi-c

unsigned int variable that increases++ the value for no apparent reason


I've a variable that increases it's value without any notice. It's behaviour can be modified by a simple printf() in some random parts of the code.

I attached my executable in gdb an got this:

101         graus[grau]++;
(gdb) print arestas
$7 = 5
(gdb) n
95      for (i = 1 ; i <= vertices ; i++) {
(gdb) print arestas
$8 = 6

And here is the code block:

unsigned grau;
unsigned graus[vertices-1];
memset(graus, 0, sizeof(graus));

for (i = 1 ; i <= vertices ; i++) {
    grau = 0;
    for (j = 1 ; j <= vertices ; j++) {
        if (getValueFromMatrix(matrix, i, j))
            grau++;
    }
    graus[grau]++;
}

Which makes no sense at since the "arestas" variable isn't even used in the loop!

The "arestas" variable is used before the loop and declared with this block of code:

matrix = createMatrix(vertices, vertices);
arestas = 0;
if (!(arestas = loadAdjacencyMatrixFromFile(file, matrix))) {
    fprintf(stderr, "ERRO: O arquivo fornecido não é valido\n");
    exit(arestas);
}

Thanks for any help.

PS: I don't know if the question was sufficiently clear, but if not please ask for the required information.


Solution

  • You have a memory overrun in the line

    graus[grau]++;
    

    because grau goes from 1 to vertices. You need to modify it to

    graus[grau - 1]++;
    

    Also graus should be declared with vertices places, not vertices - 1

    unsigned graus[vertices];