开发者

Pointer becomes nothing for no apparent reason

Greetings!

I have a simple program in qt on c. There are two pointers to type short, used to read from file and store bits from values read.

sample code:

//(input is a FILE* whic开发者_StackOverflow中文版h 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);

I've let unreliant pieces of code out. If you need to see something else please tell me.

Problem is, after like 10 or 15 operations of the loop, it crashes with "Segmentation fault" signal. It crashes on the fwrite() function.

I debugged and i use watch on sample_buffer. For some reason, on one exact step, the operation nzb_buffer[buffer_position]=sample_buffer[0]%2 makes sample_buffer become 0x0 (i belive, it becomes a null pointer).

This cannot be overflowing on nzb_buffer because buffer_position for that operation is 3 (out of 7 allocated for the particular array in malloc). And since each loop makes one write operation and shifts the carry, the operation of writing into nzb_buffer[3] has already happened before in the loop and did not nullify the pointer that time.

I am totally clueless what may be happening here. Anybody has any ideas what is going on or how do i debug it?

Thanks in advance!

PS: Added comments "what the code does"


Your exit condition for the loop seems to be misplaced. I would do:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜