DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Please tell why this code is crashing (http://www.daniweb.com/forums/thread165472.html)

tom_jerry042 Jan 1st, 2009 3:20 pm
Please tell why this code is crashing
 
Hi
snprintf is working fine when i am not using append function . But as soon as i use append function snprintf crashes . Please suggest
why snprintf is crashing after append . What is special with append function which is crashing this program
Below is the program.
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
char *s;
string name="ESACPE ";
name.append("hello '\\' ");
cout<<snprintf(s,30,name.c_str());
getch();
return 0;
}

Salem Jan 1st, 2009 3:23 pm
Re: Please tell why this code is crashing
 
Read this
http://www.daniweb.com/forums/announcement8-3.html

Then allocate some memory for s before trying to write data.

ArkM Jan 1st, 2009 7:01 pm
Re: Please tell why this code is crashing
 
After that think again. It seems you have wrote absolutely senseless code with this awkward jumble of std::string and C-string oriented snprintf ;)...

tom_jerry042 Jan 2nd, 2009 1:09 am
Re: Please tell why this code is crashing
 
hi
I know that it is awkward that i am jumbling C++ string snprintf But my point here is that this same code is working fine when i am not calling append function of std::String and it crashes when i try append function . Why code is crashing only after call of append and snprintf ?

Salem Jan 2nd, 2009 1:26 am
Re: Please tell why this code is crashing
 
As opposed to say crashing when you do this?

char *s;
string name="ESACPE ";
cout<<snprintf(s,30,name.c_str());

Who knows, dumb luck perhaps.
It's certainly got the potential to crash at any moment.

> name.append("hello '\\' ");
The fact that this made it crash does NOT imply that your previous attempt was bug-free.


Try say
char s[100]; // was char *s

tom_jerry042 Jan 2nd, 2009 1:56 am
Re: Please tell why this code is crashing
 
Thanks yes now it is working fine .

iDeveloper Jan 2nd, 2009 2:06 am
Re: Please tell why this code is crashing
 
Initialize your character pointer.

char *ptr = new char[len + 1];

Note that +1 is used to accommodate for the terminating null.

Make sure you deallocate your pointer too.

And finally read this: http://publications.gbdirect.co.uk/c..._handling.html
to learn how to handle character arrays.


All times are GMT -4. The time now is 7:53 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC