kingvashe
kingvashe

Reputation: 13

variable value change after strcpy function in C

i noticed that variable value have been changed after strcpy function,i don't know how and why this is happening. this is my code:

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

int main()
{
    int b = true;
    char ch[3];
    strcpy(ch,"int");
    printf("b value is:%d\n",b);

    return 0;
}

I even use a temporary integer variable. it's very strange , in this case, the b value is correct after strcpy but the temp is changed to 0, note that it's just happened when assigning 1 value to b and temp variables. this is the second code

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

int main()
{
    int b = true;
    int tmp=b;
    char ch[3];
    strcpy(ch,"int");
    printf("b value is:%d\n",b);

    return 0;
}

Upvotes: 0

Views: 912

Answers (3)

C.Ad
C.Ad

Reputation: 48

Firstly, you need to use number (0,1) in your boolean variables. If you want to use boolean in C as you use them in c++, you have to include stdbool.h library.

Concerning strcpy(dest, src) function, it copies the src string to dest and return à pointer to the copied string.

In reality the size of "int" is not 3 but 4 bytes. String always ends with '\0' character.

In other words :

If you don't understand, try to analyze this code :

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

   int main()
    {
        int b = 1;
        char ch[4];
        strcpy(ch,"int");
        printf("b value is:%d\n",b);

        return 0;
}

Upvotes: 0

M.Hefny
M.Hefny

Reputation: 2745

I used online compiler and selected "C++" and the error is not happening. but when I selected C++17 I got this warning " input main.cpp:9:12: warning: ‘void __builtin_memcpy(void*, const void*, long unsigned int)’ writing 4 bytes into a region of size 3 ov w=] "*

as @PaulMcKenzie mentioned this is buffer overflow case.

Upvotes: 0

ikegami
ikegami

Reputation: 385907

strcpy(ch,"int");

is equivalent to

ch[0] = 'i';
ch[1] = 'n';
ch[2] = 't';
ch[3] = 0;

Seeing as ch only has three elements (ch[0]..ch[2]), this invokes undefined behaviour.

Upvotes: 6

Related Questions