Thread: Character Array Help

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    18

    Character Array Help

    Hello all, I've encountered something that obviously should not happen in C. I declared an array of characters of say length 10 and insert 12 characters into it and it works fine. Why does this happen?

    Code:
    #include <stdio.h>
    
    char *myStrCpy(char*, char*);
    
    int main()
    {
    	char string[] = "Mary had a lamb.";
    	char copy[10] = "012345678";
    	
    	*myStrCpy( copy, string );
    	printf("%s\n", copy);
    }
    
    char *myStrCpy( char dest[], char source[] )
    {
    	int i = 0;
    	while ( source[i] != '\0' )
    	{
    		dest[i] = source[i];
    		i++;
    	}
    	dest[i] = '\0';
    	return dest;
    }

  2. #2

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by edishuman View Post
    Hello all, I've encountered something that obviously should not happen in C. I declared an array of characters of say length 10 and insert 12 characters into it and it works fine. Why does this happen?
    It happens because unlike Java and C#... C has *absolutely no runtime error checking*.

    You tell it to do something wrong and it will happily do it without even the first complaint. It's up to you as a programmer to build safeguards into your code to make sure this cannot happen.

    (Yeah, I know... WTF???? ... well, that's the way it is.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do I remove a character from character array?
    By nick753 in forum C++ Programming
    Replies: 25
    Last Post: 12-08-2010, 11:27 AM
  2. Replies: 15
    Last Post: 09-23-2010, 02:19 PM
  3. REmoving a character from a character array
    By Bladactania in forum C Programming
    Replies: 3
    Last Post: 02-11-2009, 02:59 PM
  4. Replies: 8
    Last Post: 11-12-2008, 11:25 AM
  5. Replies: 7
    Last Post: 05-11-2008, 10:57 AM