0

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.

4

2 回答 2

2

您的行中有内存溢出

graus[grau]++;

因为 grau 从 1 到顶点。您需要将其修改为

graus[grau - 1]++;

graus 也应该用顶点位置声明,而不是顶点 - 1

unsigned graus[vertices];
于 2013-09-20T04:19:14.697 回答
1

grau可以是0高达的值vertices。由于您声明unsigned graus[vertices-1],这将溢出到堆栈中的下一个内容,这似乎是arestas您的情况。

如果你得到vertices = 1,grau将是01, 因此graus需要能够包含 2 个元素, 因此unsigned graus[vertices+1];

固定大小,graus你应该很好。

然而,@WhozCraig 也提出了一个关于循环边界的有趣问题。;)

于 2013-09-20T04:30:20.490 回答