-2

I just started learning the C language. I have a good history with C# and Java though.

#include <stdio.h>     
#include <stdlib.h>
#include "info.h"
int main()
{
    int day = 24, month = 3, year = 2016;

    char name[] = "Ahmad\0";
    strcpy(name, "Ahmad(strcpy-ed string)\0"); // <-- LINE 8

    printf("%s made this program on %d-%d-%d\n", name, day, month, year);

    return 0;
}

As you can see the values have been assigned to day, month and year. But the problem is the output has competely different values. The output is this

Ahmad(strcpy-ed string) made this program on 1920234272-1684352377-1885565556

What's more interesting is if i delete line 8 it works properly. Why is this happening?

John Smith
  • 25
  • 4

2 Answers2

1

You are copying more bytes into name[] than are allocated for it-- C does not stop you from doing this. The extra bytes are overwriting other things, in this case your other variables. You are creating undefined behavior, which is a very bad thing in C programs.

antlersoft
  • 14,636
  • 4
  • 35
  • 55
0

name only has place for 8 characters, then you write into other memory, probably your other variables.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177