|
-
Dec 23rd, 2002, 10:50 AM
#1
Thread Starter
<?="Moderator"?>
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
-
Dec 23rd, 2002, 11:05 AM
#2
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Dec 23rd, 2002, 11:07 AM
#3
Thread Starter
<?="Moderator"?>
thats kinda the problem, x doesnt stay between 0-9 it can go larger.
Thanks for the help
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|