char string length and memory leak
-
28-10-2019 - |
Question
int fCount = 0;
char frameNum[7];
sprintf(frameNum, %06u", fCount);
int fCount = 0;
char frameNum[6];
sprintf(frameNum, %06u", fCount);
Q1. Which is correct, 6 or 7?
Q2. I am using VC6 and the file is sample.cpp.
I think sprintf is C. Is there a better way?
I need the char string right justified and with padded zeros.
Please don't tell me to use a newer compiler. I need to use VC6 for now.
Solution
First one is correct. There is no memory leak, by the way.
--
I think sprintf is C. Is there a better way?
Yes. C++ way:
std::stringstream ss; //#include <sstream>
ss << fCount;
std::string frameNum = ss.str();
OTHER TIPS
7, as sprintf will append a null byte '\0' to the end of the string.
Neither will be a memory leak - the data is on the stack!
Q1. Which is correct, 6 or 7?
Neither. The 6 in the format string is a minimum width, so 7 characters will not be enough if fCount >= 1000000
. The smallest size that won't overflow for any input is std::numeric_limits<int>::digits10 + 2
(to allow for all the decimal digits, the terminating character, and the sign if the input is negative). Assuming that VC6 provides <numeric_limits>
; otherwise sizeof(int)*3 + 2
is a reasonable upper bound. If you want to be sure, call snprintf
and check the return value.
Q2. I am using VC6 and the file is sample.cpp. I think sprintf is C. Is there a better way? I need the char string right justified and with padded zeros.
In most cases you're better off using C++ strings and streams, which manage their own memory and won't overflow unless you do something very strange.
std::ostringstream s;
s << setw(6) << setfill('0') << fCount;
std::string frameNum = s.str();
I'm fairly sure VC6 supports these, but it's been over a decade since I had the misfortune to battle with that compiler, and I've done my best to forget exactly how limited it was. I know you asked me not to, but I will say: use a newer compiler. The language has changed a lot in the last 15 years.