[英]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.