...
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp;
long file_size;
char *buffer;
fp = fopen("foo.bin", "rb");
if (fp == NULL) {
/* Handle Error */
}
if (fseek(fp, 0 , SEEK_END) != 0) {
/* Handle Error */
}
file_size = ftell(fp);
if (file_size == -1) {
/* Handle Error */
}
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle Error */
}
/* ... */
|
Compliant Solution
This compliant solution uses fstat() to obtain the size of the binary file.
...
However, the file position indicator returned by ftell() with a file opened in text mode is only useful in calls to fseek(). As such, the value of file_size may not necessarily be a meaningful measure of the number of characters in the file, and consequently, the amount of memory allocated may be incorrect, leading to a potential vulnerability.
...
The Visual Studio documentation for ftell() [MSDN] states:
...
Again, this indicates that the return value of ftell() for streams opened in text mode is useful only in calls to fseek() and should not be used for any other purpose.
The following code example attempts to read in 10 bytes from a text file opened in text mode. It obtains the current value of the file-position indicator by using ftell().
The code was compiled with Microsoft Visual Studio 2008 SP1 on Windows XP Professional SP3:
| Code Block |
|---|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
char a[11];
long offset;
/* The contents of foo.txt are: 0123456789 repeated 10 times separated by line feeds (ie \n) */
fp = fopen( "foo.txt", "r" );
if (fp == NULL) {
perror("fopen() error");
exit(EXIT_FAILURE);
}
/* Read 10 (n-1) bytes */
if (fgets(a, 11, fp) == NULL) {
perror("fgets() error");
fclose(fp);
exit(EXIT_FAILURE);
}
offset = ftell(fp);
if (offset == -1) {
perror("ftell() error");
fclose(fp);
exit(EXIT_FAILURE);
}
printf("offset = %ld\n", offset); /* Prints out 0.*/
return 0;
}
|
The following is printed when this example is run with the preceding setup:
| Code Block |
|---|
offset = 0
|
However, 0 is incorrect; the correct value should be 10, as evident when the file is opened in binary mode rather than text mode.
Compliant Solution
This compliant solution uses fstat() instead to the size of the text file.
...