Hello,
Moving from delphi to C
Got garbage on output while converting integer to C string. Have feeling that something wrong with char* on intToStr return. What is the right way of doing that?
char* intToStr(int value)
{
char buffer[33];
char* c;
c= itoa(value,buffer,10);
itoa() is not a C standard library function. I'll assume, given the
context, that it fills buffer with a string corresponding to the
specified value, using base 10?
The object named buffer has a lifetime that ends when your function
returns. Dereferencing a pointer that points at an object whose life
time has ended has undefined behavior. In practical terms, by the time
your program has a chance to look at the memory pointed at by the
string, it may already have been reassigned for some other use.
You have two main options.
The first is to give buffer static storage duration, which means that
it's life time extends from the beginning of the program all the way to
the end of the program; the pointer will remain valid forever. But this
means that if you call intToStr() twice, the pointer returned by the
first call will, after the second call, point to the string containing
the result the second call.
A second option is to allocate memory for the string using malloc(). The
lifetime of such memory continues until the memory has been free()d.
Problem: if you don't free() it, you've got a memory leak. You can't
free() it unless you stored the pointer somewhere so it can be passed to
free(), which is not the case in the code below:
int _tmain(int argc, _TCHAR* argv[])
{
cout<<intToStr(55)<<"\n";
I thought you said you were using C? This looks like C++, a different,
though closely related language. You'll get better answers about such
things by going to comp.lang.c++. Among other things, you could use new
and delete instead of malloc() and free(), and there are smart pointer
types you can use to avoid the necessity of explicitly using delete,
though I'm not well qualified to explain those. Also, do you realize
that you'd get a similar result by writing
cout << 55 << "\n";
It would also be more idiomatic to use endl rather than "\n".
You only need to do complicated things like this when cout() doesn't
already have the needed overloaded operator<<, for instance when you're
trying to print out a user defined type (UDT). The idiomatic C++ way to
handle that problem is to define your own operator<< overload. It should
take std:

stream& as it's first argument, your UDT as the second, and
it should return its first argument as a reference, so << overloads can
be chained together.