gpt4 book ai didi

C - Valgrind 和 "Conditional jump or move depends on uninitialised value(s)"错误

转载 作者:行者123 更新时间:2023-11-30 14:26:34 30 4
gpt4 key购买 nike

我的 OPT 算法有问题,因为 valgrind 在第 #87 行给了我错误(条件跳转或移动取决于未初始化的值)。我猜这与“break”有关,有办法解决这个问题吗?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int convert_one_char(const char c) {
if( c == '0' ) return 0;
else if( c == '1' ) return 1;
else if( c == '2' ) return 2;
else if( c == '3' ) return 3;
else if( c == '4' ) return 4;
else if( c == '5' ) return 5;
else if( c == '6' ) return 6;
else if( c == '7' ) return 7;
else if( c == '8' ) return 8;
else if( c == '9' ) return 9;
else return -1;
}

void print(int n[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d", n[i]);
if (i != size-1) {
printf(" | ");
} else {
printf(": ");
}
}
}

int main (int argc, char *argv[]) {
/* argc should be 3 */
if (argc != 3) {
printf("Napaka: Potrebna sta 2 argumenta!\n");
} else {
FILE *file = freopen(argv[2], "r", stdin);
if (file == 0) {
printf( "Napaka: 404!\n" );
} else {
int num_count = 0, len = atoi(argv[1]), buff[80], i = 0;
char c;

/* read file contents */
do {
c = getchar();
if (i%2 == 0 && isdigit(c)) {
buff[num_count] = convert_one_char(c);
num_count++;
}
i++;
} while (c != EOF);

/* print parsed file */
printf("Referencni niz: ");
for (i = 0; i < num_count; i++) printf("%d ", buff[i]);

printf("\n");

/* opt algorithm */

int frameset[len];
int flag[len];
for (i = 0; i < len; i++) {
frameset[i] = -1;
flag[i] = 0;
}

int j, s, k, tmp, available = 1, max = 0, pos, pf = 0;

for (i = 0; i < len; i++) {
frameset[i] = buff[i];
print(frameset, len);
printf("Vstavim %d\n", buff[i]);
pf++;
}

while (i < num_count) {
max = 0;
for (k = 0; k < len; k++) if (frameset[k] == buff[i]) available = 0;

if(available == 1) {
for(j = 0; j < len; j++) {

for(s = i+1; s >= 0; s++) {
if(frameset[j] == buff[s]) {
flag[j] = s; // <<< line 87
break;
}

if(s >= num_count) {
flag[j] = 100;
break;
}
}
}
for(k = 0; k < len; k++) {
if (flag[k] > max) {
max = flag[k];
pos = k;
}
}


frameset[pos] = buff[i];
print(frameset, len);
printf("Vstavim %d\n", buff[i]);

pf++;
} else {
i++;
available = 1;
}
}

printf("\n\nStevilo napak: %d\n", pf);
fclose( file );
}
}
}

最佳答案

似乎您需要将 buff[80]frameset[len] 的所有元素初始化为某些内容..也许是 0

此外,您还需要确保 len 不大于 80,否则您将在数组外部读取。

if(frameset[j] == buff[s]) {
flag[j] = s;
break;
}

关于C - Valgrind 和 "Conditional jump or move depends on uninitialised value(s)"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8944560/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com