0

Can anybody please tell me why iam getting an unexpected run-time error for the code given below. It works for two times iteration but not for more than that.

#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;
}
Zohaib
  • 363
  • 2
  • 4
  • 15
  • #define BUF_LEN (256) ...... char *chat=new char[BUF_LEN]; ...... dlete[] chat; – neohope May 07 '12 at 02:18
  • @neohope, a define is not suited for this purpose at all. There are many better ways of doing that in C++. Also, allocating an array with new needs square brackets. – chris May 07 '12 at 02:19
  • @neohope, `const` in the function you need would be preferable, but you can use a static const in a class or a const in a namespace. Even a const in the global namespace is much better than a define, as define goes before the compiler starts and ignores scope. If there's any sort of conflict, you're going to waste some time trying to figure out what the weird error you're getting is. Here's a link to a previously answered question: http://stackoverflow.com/questions/4715831/why-is-define-bad-and-what-is-the-proper-substitute – chris May 07 '12 at 02:23
  • Thank you chris :), you are right. I did not use namespace a lot in c++, your way is better. – neohope May 07 '12 at 02:26

1 Answers1

4
char *chat=new char;

This only allocates a single character. Your sprintf is blowing out this buffer.

You also don't delete this allocation, causing a leak.

Joe
  • 41,484
  • 20
  • 104
  • 125