1

After creating a char array of size 5, then I use strcpy to fill the contents of the array but with a string larger than the original size; then I use puts() to display the contents of the array an the whole string is displayed which is odd because I iterate through the array contents and it doesn't seems to me that the contents are stored in memory (but they are displayed). This is the code I am testing

#include <stdio.h>
#include <string.h>

int main(){
    char str1[5];
    int i = 0;

    strcpy(str1,"Hello world");

    puts(str1);
    printf("Size of str1: %d\n",sizeof(str1));

    for(i = 0;i < 15; i++){
            printf("%c",str1[i]);
    }
    puts(""); // Blank space
    puts(str1); // Display contents again... Different result!
    return 0;
}

Output:

Hello world
Size of str1: 5
Hello   ld  [
Hello

The 3rd line in the output is the actual contents in memory (I iterated further to verify).

I wouldn't expect the first puts(str1) to display the whole phrase but it does, also after displaying the contents I repeat puts(str1) and the output changes which seems random to me, also the array size is only 5.

Could you help me figure out what is going on?

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Omar Muñoz
  • 59
  • 1
  • 5
  • 6
    Overflowing the buffer results in undefined behavior, at which point anything can happen (including things that make no sense). – Raymond Chen Jan 23 '16 at 03:12
  • Note that this is also a case of a buffer overrun when iterating outside of the buffer. http://stackoverflow.com/a/1144159/5699206 – Joseph Young Jan 23 '16 at 03:20
  • strcpy sets a bunch of bytes starting at where you told it to. puts reads a bunch of bytes starting at where you told it to. Neither strcpy nor puts knows whether that area actually belongs to you or someone else. – user253751 Jan 23 '16 at 06:01
  • 2
    Possible duplicate of [Malloc() too small buffer](http://stackoverflow.com/questions/22531964/malloc-too-small-buffer) – user253751 Jan 23 '16 at 06:06

3 Answers3

6

strcpy doesn't know about the length of arrays/strings. It just keeps going until the string is copied (till a null character is hit).

This writes into memory you haven't allocated and is not guaranteed to return consistent results.

Joseph Young
  • 2,758
  • 12
  • 23
2

strcpy does not know how many characters to copy as mentioned by other engineer. You have to use strncpy() function, and then terminate the string by str1[4]='\0'; since 4 is the index of 5 th character, which is max size. Else the program may crash inconsistently.

Jay Kumar R
  • 537
  • 2
  • 7
0

Try this:

char str1[6];
strncpy(str1,"Hello world",5);
str1[5] = 0;

This works by using strncpy. You have to tell strncpy how many characters to actually copy. Also, you must mark the end of the string with a null (0). That is what the last line does. Note that str1[6] must have enough storage for your string plus the terminating null character.