在调用fread的时候,传参不注意导致的一个问题:
初始内存大小: buf[512];
fread(buf, 1, 1024, fp); -> 得到errno = 22
fread 调用 ->
/* define the normal version */
size_t __cdecl _fread_nolock_s(
void *buffer,
size_t bufferSize,
size_t elementSize,
size_t num,
FILE *stream
)
_fread_nolock_s 调用 ->
int __cdecl _read_nolock (
int fh,
void *inputbuf,
unsigned cnt
)
_read_nolock 调用 ->
ReadFile( (HANDLE)_osfhnd(fh), buffer, cnt, (LPDWORD)&os_read, NULL )->https://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx
ReadFile 读取的错误码,返回的错误值为:->
dosretval = GetLastError()
ERROR_NOACCESS
998 (0x3E6)
Invalid access to memory location.
->
ERROR_NOACCESS 998 winerrno.h -> https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
998 属于 EINVAL 22错误范围,
再反过来逆推分析传参->是数组越界 数组此时1024 > 512 发生越界,参数出错!!!
附上,fopen参数 http://www.cplusplus.com/reference/cstdio/fopen/
FILE * fopen ( const char * filename, const char * mode );
参数mode
C string containing a file access mode. It can be:
"r" | read: Open file for input operations. The file must exist. |
"w" | write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. |
"a" | append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist. |
"r+" | read/update: Open a file for update (both for input and output). The file must exist. |
"w+" | write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file. |
"a+" | append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist. |
The new C standard (C2011, which is not part of C++) adds a new standard subspecifier ( "x" ), that can be appended to any "w" specifier (to form "wx" , "wbx" , "w+x" or "w+bx"/"wb+x" ). This subspecifier forces the function to fail if the file exists, instead of overwriting it.
If additional characters follow the sequence, the behavior depends on the library implementation: some implementations may ignore additional characters so that for example an additional "t" (sometimes used to explicitly state a text file ) is accepted.
On some library implementations, opening or creating a text file with update mode may treat the stream instead as a binary file.