-3

For the code below, why don't I get a seg fault or some other error/warning, since my_dest is declared with only 1 char?

Doesn't it go over boundary?

#include <stdio.h>

char *MyStrcpy(char* dest, const char* src);

int main(void)
{
    char my_src[] = "1234567890";
    char my_dest[1];
    MyStrcpy(my_dest, my_src);
    printf("new dest: %s\n", my_dest);
}

char *MyStrcpy(char* dest, const char* src)
{
    char* addr = dest;
    while (*dest++ = *src++);
    return addr;
}
wuyefeibao
  • 237
  • 1
  • 9
  • 4
    "undefined behavior" != "instant crash always". this is getting really boring. – The Paramagnetic Croissant Jul 21 '14 at 19:42
  • Unless this is being done entirely for educational purposes, don't write your own string routines. Just use the secure versions of the functions that came with your compiler. – Chuck Walbourn Jul 21 '14 at 19:45
  • @ChuckWalbourn - What are you talking about? ( _secure versions of the functions_ ) – ryyker Jul 21 '14 at 19:48
  • In the case of Microsoft platforms that would be: [strcpy_s](http://msdn.microsoft.com/en-us/library/td1esda9.aspx). Most of the 'original' C string library methods have lots of security risks due to buffer overruns. – Chuck Walbourn Jul 21 '14 at 19:50
  • 3
    @ChuckWalbourn: Leave me alone with their deprecation crusade and such nuisances. – Deduplicator Jul 21 '14 at 19:51
  • Malware is a bit more than a damn nuisance... In any case, my point was "roll your own" string functions is a bad idea. In most case "undefined behavior" is "potential exploit" – Chuck Walbourn Jul 21 '14 at 19:53

1 Answers1

4

Your program invokes undefined behavior as you are writing past the end of an array.

In C undefined behavior means anything can happen: your program can crash or crash every Thursday.

C does not require the compiler to issue a warning if the program invokes undefined behavior as it may be very difficult for the compiler to detect all the undefined behavior invocations. However C allows the compiler to issue a warning or to stop the translation but doesn't require it.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 1
    Nicely stated. Can also be summarized with some humor in two words: ***[nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html)***. – ryyker Jul 21 '14 at 20:20