簡體   English   中英

有關strcpy溢出的問題

[英]Questions about strcpy overflows

我正在使用這樣的簡單主線

#include <string.h>

int main(int argc, char **argv)
{
        char buf[256];
        strcpy(buf, argv[1]);
}

我知道,如果編譯了該主程序,它將產生值為1的'argc',並且argv [1]將不存在此程序中定義的值。 但是,盡管argv [1]作為const char *傳遞,但argv [1]表示的內存地址盡管未在此程序中定義,但不會被程序修改。 所以我的問題是為什么strcpy無法獲取此char並將其寫入buf? 另外,為什么argc = 1?

您可以。 您可能會遇到的唯一問題是,如果argc小於2,或者argv [1]大於255個字節(加上字符串終止字符)。

在大多數系統上,argv []數組的布局具有相同的布局。 例如,假設程序是從命令行執行的:

>./myprog cookie monster

argv[0]    Contains the path where the executing program resides in the filesystem.
           So the actual value is something like: '/home/mahonri/test/test'
           This value is provided by the operating system.

argv[1]    Will contain the string: 'cookie'
           This value is provided (optionally) by the user.

argv[2]    will contain the string: 'monster'
           This value is provided (optionally) by the user.

argc       will be '3', because there are three argv elements; 0, 1 and 2.

對於問題代碼,如果argc為'1',則僅argv [0]初始化;否則為0。 如果代碼隨后嘗試訪問argv [1]或argv [2],則會發生不可預測的事情。

對您的問題的簡單回答“所以我的問題是為什么strcpy無法抓住這個char並將其寫入buf”是argv [1]未被視為常量char *,正如您提到的那樣,但是它將是NULL指針,請參見C §5.1.2.2.1,第2段。 在您的情況下,將發生未定義的行為。

至於“為什么argc = 1?” 值得關注,這取決於您要傳遞的參數數量。 命令行參數是非常基本的。 做研究。

暫無
暫無

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

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