问候!
我在qt上有一个简单的程序。 有两个指向short类型的指针,用于从文件读取和存储读取值的位。
示例代码:
//(input is a FILE* which is opened and passed to the function)
//(output is also a FILE* which is also opened and passed to the function)
//1. Variables declaration
short* sample_buffer;
int buffer_size=1;
short samples_read;
unsigned long value_x=7;
short* nzb_buffer;
short buffer_position=-1;
int i;
//2.Memory allocation
sample_buffer= malloc(sizeof(short)*buffer_size);
nzb_buffer = malloc(sizeof(short)*value_x);
....
//3. Read from infile, one short at time, process and write it to outfile
do
{
//3.1. Read from input file
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
//3.2. Switch position inside nzb_buffer one to the right,
// going back to zero if out of bounds
buffer_position=(buffer_position+1)%value_x;
....
//3.3. Put least significant bit of the just read short into nzb_buffer
nzb_buffer[buffer_position]=sample_buffer[0]%2;
....
//3.4. Write the short we just read from infile to the outfile
for (i=0;i<samples_read;i++)
{
fwrite(sample_buffer,sizeof(short),1, output);
}
} while(samples_read==buffer_size);
我让不可靠的代码片段出来了。如果你需要看别的东西,请告诉我。
问题是,在循环的10或15次操作之后,它会因“分段故障”信号而崩溃。它在fwrite()函数上崩溃。
我调试了,我在sample_buffer上使用watch。由于某种原因,在一个确切的步骤,操作nzb_buffer [buffer_position] = sample_buffer [0]%2使sample_buffer变为0x0(我相信,它变成空指针)。
这不能在nzb_buffer上溢出,因为该操作的buffer_position是3(在malloc中为特定数组分配的7个)。并且由于每个循环进行一次写操作并移位进位,因此写入nzb_buffer [3]的操作在循环之前就已经发生,并且没有使指针无效。
我完全不知道这里可能发生什么。 任何人都有任何想法发生了什么或如何调试它?
提前致谢!
PS:添加了评论“代码的作用”
答案 0 :(得分:1)
循环的退出条件似乎是错误的。我愿意:
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
while(samples_read==buffer_size){
[...]
samples_read = fread(sample_buffer,sizeof(short),buffer_size, input);
}