Question

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.

Was it helpful?

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];

OTHER TIPS

grau can be a value 0 up to vertices. Since you declare unsigned graus[vertices-1], this will overflow into whatever is next on the stack, which seems to be arestas in your case.

If you got vertices = 1, grau will be either 0 or 1, therefore graus needs to be able to contain 2 elements, therefore unsigned graus[vertices+1];

Fix the size of graus and you should be good.

However, @WhozCraig also raises an interesting question about the loop bounds. ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top