[英]printf sometimes prints extra garbage
I'm parsing through a .ppm
file, using fgetc
to read a single byte at a time, and then converting them to floats by dividing by 255.0 to get colors for use in OpenGL code. 我正在解析一个.ppm
文件,使用fgetc
读取一个字节,然后通过除以255.0来将它们转换为浮点数,以获取供OpenGL代码使用的颜色。 This is easy. 这很容易。 I print the numbers out for debugging purposes using printf("%f %f %f\\n", color[0], color[1], color[2]);
我使用printf("%f %f %f\\n", color[0], color[1], color[2]);
打印出数字以进行调试printf("%f %f %f\\n", color[0], color[1], color[2]);
. 。 Most of the time this works well (see the first line), but occasionally it prints out extra garbage (see the second line). 在大多数情况下,此方法运行良好(请参阅第一行),但有时会打印出多余的垃圾(请参见第二行)。
0.086275 0.031373 0.000000
0.133333 0.000000 0.00<BA><B9>9?<D1><D0><D0>=<99><98>^X>3 0.078431 0.000000
Any ideas why this might be? 任何想法为什么会这样?
UPDATE: 更新:
float *read_eight_bit(FILE *file, int rows, int cols)
{
float *data = (float *)malloc(rows*cols*3*sizeof(float));
int c;
int i, j, k;
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
for(k = 0; k < 3; k++) {
if((c = fgetc(file)) != EOF) {
data[get_index(i, j, k, rows, cols)] = c/255.0f;
}
else {
perror("reached unexpected EOF");
free(data);
return NULL;
}
}
return data;
}
This is the actual code that reads things in. 这是读取内容的实际代码。
The only explanation I can think of without seeing more code is that the stack is messed up somehow, possibly through a buffer over- or underrun (writing outside an array). 在没有看到更多代码的情况下,我能想到的唯一解释是,堆栈可能以某种方式被弄乱了,可能是由于缓冲区溢出或溢出(在数组外部写入)造成的。
I'd recommend running your code through cppcheck , as it can detect many of these sorts of problems. 我建议通过cppcheck运行您的代码,因为它可以检测到许多这类问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.