Author: Bo Persson
Date: 13:41:01 11/30/01
Go up one level in this thread
On November 30, 2001 at 00:22:29, Miguel A. Ballicora wrote:
>On November 28, 2001 at 19:15:34, Dann Corbit wrote:
>
>>If you have boundschecker or something like that, it will cough out these sorts
>>of problems in a heartbeat.
>
>Yes. Is there freeware or open source code for that?
>
>Anyway, I found the bug!!!
>long story short: sloppy use of strncpy.
>
>strncpy can overwrite memory if the string target cannot hold all the characters
>to be tranferred because it padds after the end with zeros!
>
>I decide it no to use strncpy anymore and write my own "mystrncpy" routine.
>Also, I have to standarize the size of some strings or (better) pass
>the amount of characters that a string can receive to a function (in this case
>getcmd, see below).
>I was never aware of the risks of using strncpy. Besides, it does not do
>what I need.
>
>The bug was something like this:
>
>int main ()
>{
> char command[80]; /* 80 is wrong!!! even though looks big!!!*/
> /* have to use 255 as inside func!!! */
> int x; /* this will be overwritten */
> ...
> getcmd (command);
>}
>
>void getcmd (char *t)
>{
> char s[255];
> ...
> inputline(s); /* receive a short line from a file */
> ...
> modify s to get a command
> ...
> strncpy (t, s, 255); /* it will send 255 chars to t no matter what!!!! */
>
>}
>
>bottom line, 80 != 255.
>
>Happy and relieved,
>Miguel
What if 255 doesn't help either??
This is one reason why some of us like C++ better. Try this:
#include <string>
int main()
{
std::string command = getcmd();
int x; // Never overwritten!
...
}
std::string getcmd()
{
std::string s;
std::getline(somestream, s);
...
return s;
}
Just a thought! :-)
Bo Persson
bop2@telia.com
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.