简体   繁体   English

有关strcpy溢出的问题

[英]Questions about strcpy overflows

I am using a simple main like this 我正在使用这样的简单主线

#include <string.h>

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

I understand that if compiled, this main will produce 'argc' with a value of one, and argv[1] would not exist as defined in this program. 我知道,如果编译了该主程序,它将产生值为1的'argc',并且argv [1]将不存在此程序中定义的值。 However, the memory address represented by argv[1], although not defined in this program, would not be modified by the program, as argv[1] is passed as a const char * . 但是,尽管argv [1]作为const char *传递,但argv [1]表示的内存地址尽管未在此程序中定义,但不会被程序修改。 So my question is why strcpy cannot grab this char and write it into buf? 所以我的问题是为什么strcpy无法获取此char并将其写入buf? Also, why is argc = 1? 另外,为什么argc = 1?

Q:So my question is why strcpy cannot grab this {argv[1]} char and write it into buf? 问:所以我的问题是为什么strcpy无法抓住这个{argv [1]}字符并将其写入buf?

You can. 您可以。 The only problems you might encounter is if argc is less than 2, or if argv[1] is larger than 255 bytes (plus the string termination character). 您可能会遇到的唯一问题是,如果argc小于2,或者argv [1]大于255个字节(加上字符串终止字符)。

Q:Also, why is argc = 1? 问:此外,为什么argc = 1?

On most systems, the lay-out of the argv[] array has the same layout. 在大多数系统上,argv []数组的布局具有相同的布局。 For example, assume that a program was executed from the command-line: 例如,假设程序是从命令行执行的:

>./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.

In the case of the question code, if argc is '1', then only argv[0] is initialized; 对于问题代码,如果argc为'1',则仅argv [0]初始化;否则为0。 and unpredictable things will happen if the code then attempts to access argv[1] or argv[2]. 如果代码随后尝试访问argv [1]或argv [2],则会发生不可预测的事情。

The simple answer to your question "So my question is why strcpy cannot grab this char and write it into buf" is argv[1] is not treated as constant char *, as you mentioned, but it will be a NULL pointer, see C §5.1.2.2.1, para2. 对您的问题的简单回答“所以我的问题是为什么strcpy无法抓住这个char并将其写入buf”是argv [1]未被视为常量char *,正如您提到的那样,但是它将是NULL指针,请参见C §5.1.2.2.1,第2段。 In your case undefined behaviour will occur. 在您的情况下,将发生未定义的行为。

As far as "why is argc = 1?" 至于“为什么argc = 1?” is concern, it depends on number of arguments you are passing. 值得关注,这取决于您要传递的参数数量。 It is very basic to command line argument. 命令行参数是非常基本的。 Do a research . 做研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM