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;
}
4
  • #define BUF_LEN (256) ...... char *chat=new char[BUF_LEN]; ...... dlete[] chat; Commented May 7, 2012 at 2: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. Commented May 7, 2012 at 2: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: stackoverflow.com/questions/4715831/… Commented May 7, 2012 at 2:23
  • Thank you chris :), you are right. I did not use namespace a lot in c++, your way is better. Commented May 7, 2012 at 2:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.