Zohaib
Zohaib

Reputation: 363

Unexpected Run time error with simple code

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;
}

Upvotes: 0

Views: 86

Answers (1)

Joe
Joe

Reputation: 42607

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.

Upvotes: 4

Related Questions