【问题标题】:Unexpected Run time error with simple code使用简单代码的意外运行时错误
【发布时间】:2012-05-07 10:14:27
【问题描述】:

谁能告诉我为什么下面给出的代码会出现意外的运行时错误。它适用于两次迭代,但不止于此。

#include<iostream>
#include<fstream>
#include<string>

using namespace std;
void print(string hmm)
{
         ofstream ko(hmm.c_str(),ios::trunc);
         ko<<"chacho";
         ko.close();
}

int main(){
for(int i=0;i<5;i++)
{
        char *chat=new char;
        sprintf(chat,"%d%s",i,"_num.txt");
        string rat=chat;

        print(rat);
}

system("pause");
return 0;
}

【问题讨论】:

  • #define BUF_LEN (256) ...... char *chat=new char[BUF_LEN]; ...... dlete[] 聊天;
  • @neohope,定义根本不适合这个目的。在 C++ 中有许多更好的方法可以做到这一点。此外,分配带有新需求方括号的数组。
  • @neohope, const 在您需要的函数中会更可取,但您可以在类中使用静态 const 或在命名空间中使用 const。即使是全局命名空间中的 const 也比定义好得多,因为定义在编译器启动之前进行并忽略范围。如果有任何形式的冲突,您将浪费一些时间试图弄清楚您遇到的奇怪错误是什么。这是之前回答的问题的链接:stackoverflow.com/questions/4715831/…
  • 谢谢你,克里斯 :),你是对的。我在 c++ 中没有大量使用命名空间,你的方式更好。

标签: c++


【解决方案1】:
char *chat=new char;

这只分配一个字符。您的 sprintf 正在耗尽此缓冲区。

你也没有删除这个分配,导致泄漏。

【讨论】:

    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 2022-01-26
    • 2021-11-05
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多