简体   繁体   English

C语言中带有换行符的printf的怪异行为

[英]Weird behavior of printf in C++ with a newline character

This could be simple or lame question. 这可能是简单的问题,也可能是la脚的问题。 I have been playing with printf function in C++. 我一直在玩C ++中的printf函数。 When I execute following code on Debian Wheezy with any 9 character argument (eg:"argument1") ; 当我在Debian Wheezy上使用任何9个字符的参数(例如:“ argument1”)执行以下代码时;

#include<stdio.h>

int main(int argc, char** argv){

    printf(argv[1]+'\n');

}

the out put was; 输出是

SSH_AGENT_PID=4375

Then I checked the environment variable $SSH_AGENT_PID and its value is 4375. 然后,我检查了环境变量$SSH_AGENT_PID ,其值为4375。

Could you please tell me what is going on with my code ? 您能告诉我我的代码怎么了吗? (I tried to examine the disassembled code in gdb. But my assembly knowledge is poor to understand exactly whats going on) (我试图检查gdb中的反汇编代码。但是我的汇编知识很差,无法确切了解发生了什么情况)

Simple fix: 简单修复:

printf("%s\n", argv[1]);

This is an improvement on your code for two reasons: First, it's generally a good idea to have the first argument to printf be a string constant, as this prevents printf code injection. 这是对代码的改进,有两个原因:首先,将printf的第一个参数设为字符串常量通常是一个好主意,因为这样可以防止注入printf代码。 Second, it fixes the bug because as @Captain Oblivious pointed out, the code you wrote doesn't do what you think it does. 其次,它修复了该错误,因为正如@Captain Oblivious指出的那样,您编写的代码无法实现您认为的功能。

char* strings and string literals and character literals can't be added together. char*字符串以及字符串文字和字符文字不能一起添加。 You need to create a new string and use strcat to concatenate one to the other. 您需要创建一个新字符串,并使用strcat将一个字符串连接到另一个字符串。

What you're actually getting is undefined behavior, since you're adding some constant to a pointer and not checking that you've passed the end of the string. 实际上,您得到的是未定义的行为,因为您要向指针添加一些常量,而不是检查是否已传递字符串的末尾。 It's only a coincidence that the output was readable at all and that your program didn't crash. 巧合的是,输出完全可读并且您的程序没有崩溃。

If C++ is an option you can use std::string instead, which does allow + to concatenate two strings. 如果C ++是一个选项,你可以使用std::string代替,这确实允许+连接两个字符串。

To explain what you are seeing from argv[1] + '\\n' . 解释您从argv[1] + '\\n'中看到argv[1] + '\\n' This is pointer plus integer (character constants have type int in C). 这是指针整数 (字符常量在C中的类型为int )。

The definition of that in C is that the pointer is advanced by as many units as are in the integer. C语言中对它的定义是,指针以整数形式前进许多单位。 \\n is 10 in ASCII so this will advance the pointer by 10 characters. \\n ASCII码为10 ,因此会将指针前移10个字符。 If your string is shorter than 10 then you're now reading whatever is in memory beyond the end of that string. 如果您的字符串小于10,则您现在正在读取该字符串末尾之外的内存内容。

The fix suggested by Ben Braun is a good one; 本·布劳恩(Ben Braun)提出的解决方案很好。 another option is puts( argv[1] ); 另一个选择是puts( argv[1] ); which will output the string without doing any printf-like translations, and output a newline. 它将输出字符串而不进行任何类似printf的翻译,并输出换行符。

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

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