繁体   English   中英

C ++分配内存问题

[英]c++ allocating memory problem

我在c ++中分配内存时遇到了一个奇怪的问题,我正在创建一个缓冲区并将文件内容读入其中。 问题是分配不正确,并且在打印结束时出现了奇怪的字符...文件的内容为“ Hello” ...我坐在上面几个小时...可能是什么问题? :(

void main()
{
 FILE *fp;
 char *buffer;
 long file_size;
 size_t result;

 fp = fopen("input.txt","r");
 if (fp == NULL) { fputs("File Error",stderr); exit(1); }

 //get file size
 fseek(fp, 0, SEEK_END);
 file_size = ftell(fp);
 rewind(fp);

 //allocate memory to contain the whole file size
 buffer = new char[file_size];

 if (buffer == NULL) { fputs("Cannot allocate memory space",stderr); exit(2); }

 //copy the file into the buffer
 result = fread(buffer, 1, file_size, fp);
 if (result != file_size) { fputs("Reading error",stderr); exit(3); }

 cout<<buffer;
 fclose(fp);
 delete buffer;
 }

您不是以零结尾的缓冲区,所以它不是有效的C / C ++字符串。

尝试以下更改:

//allocate memory to contain the whole file size, plus one char for termination
buffer = new char[file_size + 1];

if (buffer == NULL) { fputs("Cannot allocate memory space",stderr); exit(2); }

//copy the file into the buffer
result = fread(buffer, 1, file_size, fp);
if (result != file_size) { fputs("Reading error",stderr); exit(3); }

// terminate buffer, so it becomes a valid string we can print

buffer[file_size] = '\0';    
cout<<buffer;

为终止符再分配一个地方。 并将其放在缓冲区的末尾。 这可能会解决您的问题。

buffer = new char[file_size + 1];
buffer[file_size] ='\0';

对于cout<<buffer输出, buffer必须包含一个以NULL结尾的字符串,这样cout<<buffer意义。

当你在C ++中 ,有什么讲反对使用 C ++?

请参阅: http : //www.cplusplus.com/doc/tutorial/files/

edit2:响应Neil(初始版本打印一个空行0):

int main () {
        std::ifstream i ("main.cpp");
        std::string str;
        for (int line=0; getline (i, str); ++line) {
                std::cout << line <<  ':' << str << '\n';
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM