gpt4 book ai didi

c - 指针无缘无故变为空

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:05 25 4
gpt4 key购买 nike

您好!

我在 qt on c 中有一个简单的程序。有两个指向 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: 添加注释“代码的作用”

最佳答案

您的循环退出条件似乎放错了地方。我会这样做:

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);
}

关于c - 指针无缘无故变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4680017/

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