Hi,
I got this message "Windows has triggered a breakpoint in inout.exe. This may be due to a corruption of the heap, and indicates a bug in inout.exe or any of the DLLs it has loaded. The output window may have more diagnostic information" while debugging the following program in VC 2005 Express:

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

int main(void) {
    
	char file[]="test.txt";

	FILE*fp=fopen(file,"w");
	for (int i=0;i<200;i++) fprintf(fp,"%d ",255);
	fclose(fp);

	fp=fopen(file,"r");
	unsigned char*ptr;
	ptr=(unsigned char*)malloc(5*sizeof(unsigned char));
	for (int i=0;i<5;i++)fscanf(fp,"%d",ptr+i);
	fclose(fp);

	free(ptr);
                return 0;
}

What's the problem with my code? Thanks in advance!

>>ptr=(unsigned char*)malloc(5*sizeof(unsigned char));

you are only allocating 5 bytes to hold 5 integers! and ptr needs to be an int pointer, not a char pointer. Change that line to int* ptr= malloc(5*sizeof(unsigned int));

Thanks.

In fact I just made up the "test.txt" file. In my real case, I have to read in data ( each is an integer and ranges from 0 to 255) from a file into an unsigned char array that are dynamically allocated.

Since an unsigned char can hold a value as large as 255, is there something else wrong? Is it correct to use the conversion specifier "d" with unsigned char in "fscanf"?

Hi,Thanks!
I still have the same questions:
Since an unsigned char can hold a value as large as 255, why bother to use integer as intermediate?
Is there something else wrong? Is it correct to use the conversion specifier "d" with unsigned char in "fscanf"? If it is not, which conversion spcifier is proper for unsigned char?

>Is it correct to use the conversion specifier "d" with unsigned char in "fscanf"?
Nope. You have no idea how your implementation of fscanf will work. It's especially dangerous to say you'll pass a pointer to a type of one size and actually pass a pointer to a type of a smaller size. By using an intermediate int variable for the input, you at least have more control over when and how the assignments are performed:

for ( int i = 0; i < 5; i++ ) {
  int temp;

  fscanf ( fp, "%d", &temp ); /* Always safe[1] */

  /* Now you can verify the value before converting! */
  if ( 0 <= temp && temp <= 255 )
    ptr[i] = temp;
  else {
    /* Handle the error */
  }
}

>If it is not, which conversion spcifier is proper for unsigned char?
In C99, you can say %hhd to read an unsigned char as an integral value rather than a character. In C89 and C++, you're SOL and have to use the intermediate if you want to be safe.

[1] It's not always safe because *scanf doesn't check for arithmetic overflow. For example, if the file contains 999999999999999999999 somewhere, you're borked.

This article has been dead for over six months. Start a new discussion instead.