Board index » cppbuilder » itoa blowing up ? why?
peter
CBuilder Developer |
peter
CBuilder Developer |
itoa blowing up ? why?2005-08-04 12:02:51 AM cppbuilder9 i have a function: [code] char* getZipFileExtension(int number){ char *buf; char *num; itoa(number,buf,10); //do some stuff with this.... }//end function [/code] i was testing it, and the itoa function blows up the second time i call it. I enter the function the first time, everything works OK, then when I come back the second time it blows up. Can anyone tell me why this is happening? I would appreciate any help. |
Ed Mulroy
CBuilder Developer |
2005-08-04 12:29:13 AM
Re:itoa blowing up ? why?Quotechar *buf; of an array of characters to hte variable. Therefore itoa is being asked to write to a random address in memory. The result of doing that can be unpleasant. Try this instead: char buf[33]; ... itoa(number,buf,10); . Ed Quotepeter wrote in message |
Remy Lebeau (TeamB)
CBuilder Developer |
2005-08-04 01:44:09 AM
Re:itoa blowing up ? why?
"peter" < XXXX@XXXXX.COM >wrote in message
Quotei was testing it, and the itoa function blows up the second time i call pointer is not even intialized so it initially points to random memory. As such, you will have undefined behavior for the rest of the process's lifetime because you could be corrupting memory. The fact that sometimes your code crashes and sometimes it doesn't is just a side effect of undefined behavior, since it depends on which memory is being altered each time. QuoteI enter the function the first time, everything works char* getZipFileExtension(int number) { char buf[12] = {0}; // <-- ALLOCATE STORAGE FOR THE BUFFER!!! itoa(number, buf, 10); // .... } Gambit {smallsort} |
Liz Albin
CBuilder Developer |
2005-08-04 03:11:18 AM
Re:itoa blowing up ? why?
On 3 Aug 2005 09:02:51 -0700, peter wrote:
Quote[code] variable that will disappear any way you could try something more like char * getZipFileExtension(char * buf,int number) { itoa(number,buf,10) return buf; } int main() { char buf[20]; getZipFileExtension(buf,3); std::cout << buf << std::endl; } Although I think using boost::lexical_cast would be more sensible: www.boost.org/libs/conversion/lexical_cast.htm #pragma hdrstop #include <iostreams> #include <string> #include <boost/lexical_cast.hpp> #pragma argsused int main(int argc, char* argv[]) { std::string thing = boost::lexical_cast <std::string>(3); std::cout << thing << std::endl; return 0; } -- good luck, liz |