1

我试图不断地从不同的文件将数据读入 unsigned char* 类型的缓冲区。但是,在读取下一个文件之前,我似乎无法将缓冲区设置为 NULL。

这里只是相关的代码:

#include <stdio.h>
#include <fstream>


int
 main (int argc, char** argv) { 

     FILE* dataFile = fopen("C:\\File1.txt", "rb");
     unsigned char *buffer = NULL;
     buffer = (unsigned char*)malloc(1000); 
     fread(buffer,1,1000,dataFile);
     fclose(dataFile);

     dataFile = fopen("C:\\File2.txt", "rb");
     buffer = NULL;
     fread(buffer,1,1000,dataFile);
     fclose(dataFile);

     system("pause");
     return 0; 

}

我遇到的错误是在此行的第二次出现:fread(buffer,1,1000,dataFile);

我得到的错误是:

调试断言失败!表达式:(缓冲区!= NULL)

它指向 fread.c 的第 147 行,基本上是:

/* validation */
_VALIDATE_RETURN((buffer != NULL), EINVAL, 0);
if (stream == NULL || num > (SIZE_MAX / elementSize))
{
    if (bufferSize != SIZE_MAX)
    {
        memset(buffer, _BUFFER_FILL_PATTERN, bufferSize);
    }

    _VALIDATE_RETURN((stream != NULL), EINVAL, 0);
    _VALIDATE_RETURN(num <= (SIZE_MAX / elementSize), EINVAL, 0);
}

我在谷歌上找到了将缓冲区指针指向 NULL 的方法,并尝试了各种建议,但似乎都没有奏效。任何人都可以澄清将其设置为 NULL 的正确方法是什么?

4

2 回答 2

5

You can't say buffer = NULL because fread wil try to dereference it. Dereferencing NULL is one of the things that are certainly and completely illegal in C++. In effect you're losing what you got from malloc. Perhaps you're looking for memset and trying to zero the buffer:

memset(buffer, 0, 1000);

However, you don't need to do this before calling fread. There's simply no reason since fread will write the buffer anyway: it doesn't care if it's zeroed or not.


As a side note: you're writing very C-ish code in what I suspect is C++ (given your fstream header). There are better-suited I/O options for C++.

于 2012-08-22T18:09:41.063 回答
5

Your buffer is a pointer.

When you do this:

buffer = (unsigned char*)malloc(1000); 

you allocate some space in memory, and assign its starting position to buffer. Remember, buffer holds the address of the beginning of the space, that's all. When you do this:

buffer = NULL;

you have thrown away that address.

EDIT:

C++ style, without dynamic memory:

#include <fstream>    
using std:: string;
using std:: ifstream;

void readFromFile(string fname)
{
  char buffer[1000];
  ifstream fin(fname.c_str());
  fin.read(buffer, sizeof(buffer));
  // maybe do things with the data
}

int main ()
{
  readFromFile("File1.txt");
  readFromFile("File2.txt");
  return 0;
}

There's no need to erase the contents of the buffer. If the cost of allocating and deallocating the buffer with each call is too much, just add static:

  static char buffer[1000];

It will be overwritten each time.

于 2012-08-22T18:11:07.177 回答