簡體   English   中英

C中strcpy函數后的變量值變化

[英]variable value change after strcpy function in C

我注意到在 strcpy 函數之后變量值已經改變,我不知道這是如何以及為什么發生的。 這是我的代碼:

#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;
}

我什至使用臨時整數變量。 很奇怪,在這種情況下,strcpy 后 b 值是正確的,但 temp 更改為 0,注意它只是在為 b 和 temp 變量分配 1 值時發生的。 這是第二個代碼

#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;
}
strcpy(ch,"int");

相當於

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

看到ch只有三個元素( ch[0]..ch[2] ),這會調用未定義的行為。

我使用了在線編譯器並選擇了“C++”並且錯誤沒有發生。 但是當我選擇 C++17 時,我收到了這個警告“ input main.cpp:9:12: warning: 'void __builtin_memcpy(void*, const void*, long unsigned int)' 將 4 個字節寫入大小為 3 ov 的區域w=]"*

正如@PaulMcKenzie 提到的,這是緩沖區溢出的情況。

首先,您需要在布爾變量中使用數字 (0,1)。 如果您想在 C 中使用布爾值,就像在 C++ 中使用它們一樣,您必須包含 stdbool.h 庫。

關於 strcpy(dest, src) 函數,它將 src 字符串復制到 dest 並返回指向復制字符串的指針。

實際上,“int”的大小不是 3 而是 4 個字節。 字符串總是以 '\\0' 字符結尾。

換句話說 :

如果你不明白,試着分析這段代碼:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM