-
sprintf problem
Code:
for(int x=0;x<5;x++)
{
char * strVal;
strVal = new char[4];
sprintf(strVal, "%s%d%g", '<', x, '>');
cout<<strVal<<endl;
delete[] strVal;
}
when i compile this there isnt any errors, but at runtime it say "memory could not be read".
any ideas how to fix this problem. Thanks
-
You have several memory access violations there.
The first is simple: you allocate memory for 4 chars, this means the string can be at most 3 characters long. sprintf tries to write more to it, it has to fail.
The second is more subtle and is the everlasting problem of all the *printf family: the compiler can't perform any typechecking.
Your format string is
"%s%d%g": one c-style-string, one integer (32-bit) and one floating point number (64-bit) to be formatted to simple or scientific format, whichever is more appropriate (by the definition of the ANSI C standard).
Your arguments are:
'<', x, '>': One character, one integer(32-bit) and another character.
Matched up this means
wants string, gets character
wants integer, gets integer
wants floating point, gets character
Disaster is inevitable.
The solution, of course, is to correct the format flags, and as long as you know that x stays in the range [0-9] you don't even need more memory.
-
thats kinda the problem, x doesnt stay between 0-9 it can go larger.
Thanks for the help :)