Re: buffer overflow



Roman Mashak wrote:

can't realize what's happening in this code snippet:

int main(int argc, char *argv[])
{
char buf[256];
strcpy(buf, argv[1]);
...
}

Debugger shows argv[1] as NULL and as a result I get 'segmentation
fault' on 'strcpy' call. I can't figure out why NULL is not a proper
in this case, standard doesn't prohibit it in string functions (at
least I have not found it).

However the standard does require a proper string to copy into
buf. A string is a sequence of bytes, possibly empty, followed by
a '\0' byte. A NULL pointer doesn't point to anything, so there is
no place for that '\0'. So you need a statement such as:

if (argv[1]) strcpy(buf, argv[1]);
else buf[0] = '\0';

Of course argv[1] may not even exist, so you should also guard by:

if (argc > 1) ...

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


.



Relevant Pages

  • Re: Destructor: not gauranteed to be called?
    ... >>> the ToStringmethod to a Char[] it returns with the EXACT SAME ... >>> the standard and might break someone's existing code. ... ToString is not part of the C++ ... The fact yhat you require or expect a Charto act as a string is a sign ...
    (microsoft.public.dotnet.languages.vc)
  • Re: substring finding problem!
    ... peculiar notion of not using standard string functions. ... char *str, ... I added the one because when both string and sub string are equal length the ... i cant compare remaining_len>= 0 since that'll always be true for unsigned. ...
    (comp.lang.c)
  • Re: how to convert char* to File *
    ... char* for the content,and I think saving char* to a file and opening it ... So you have a string, and you want to arrange for that string to be ... from a disk file will be too slow. ... There's nothing in the C standard that says a FILE* has to be ...
    (comp.lang.c)
  • Re: UDB and pointer increments and decrements
    ... if s points to the start of a string and e becomes less than s then e is ... not really pointing to defined char. ... One of the reasons the Standard ... worth pointing out the sacrifice and suggesting safer alternatives. ...
    (comp.lang.c)
  • Re: char*
    ... that the char* points to? ... I don't know at forehand how long the string is. ... If it's a proper string, terminated with a null character, then you can ...
    (comp.lang.c)