strcat 古怪的行为
我编写了这个简单的 C 程序,但不太明白 strcat
long sum(long col, char* path, char* path2){
printf("%s\n",path2);
strcat(path,".endlines");
printf("%s\n",path2);
return 0;
}
int main(int argc, char* argv[]) {
int n=atoi(argv[1]);
sum(n,argv[2],argv[3]);
exit(EXIT_SUCCESS);
}
strcat 的这种奇怪行为应用于路径,但最终路径2也被修改了。如果有人让我知道发生了什么事,我将非常感激:) 谢谢
Run
./program 3 example/mountdir/location2.csv 示例/rootdir/location2.csv
输出:
示例/rootdir/location2.csv
结束线
I wrote this simple C program and couldn't quite figure out this bizarre behavior of strcat
long sum(long col, char* path, char* path2){
printf("%s\n",path2);
strcat(path,".endlines");
printf("%s\n",path2);
return 0;
}
int main(int argc, char* argv[]) {
int n=atoi(argv[1]);
sum(n,argv[2],argv[3]);
exit(EXIT_SUCCESS);
}
strcat is applied on path, but path2 is eventually modified as well. I would very much appreciate if someone let me know what was happening :) thanks
Run
./program 3 example/mountdir/location2.csv
example/rootdir/location2.csv
output:
example/rootdir/location2.csv
endlines
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您超出了缓冲区。原始的 argv[2] 和 argv[3] 在内存中很可能是连续的。当您
strcat
到 argv[2] 的末尾时,它正在写入 argv[3] 指向的内存。您需要分配新的缓冲区来保存您尝试创建的较大字符串。You are overrunning a buffer. The original argv[2] and argv[3] are very likely consecutive in memory. When you
strcat
onto the end of argv[2], it is writing onto the memory argv[3] points at. You need to allocate new buffers to hold the larger strings you are trying to make.首先,您无法写入 argv[2]。 (这样做会产生依赖于实现或未定义的行为。区别并不重要:不要这样做)。
第二;混乱在哪里?您可能在 argv[1] 之后使用 argv[2] 布置了内存,因此它看起来像“example/mountdir/location2.csv\0example/rootdir/location2.csv”。 argv[ 2 ] (path) 指向第一个“e”,path2 指向空字节后面的“e”。当您 strcat 到路径时,您正在从 \0 开始写入数据,因此 \0 被替换为“.”,“e”被结尾行的“e”替换,等等,现在 path2 指向第二个字符串“.endlines”的字符,因此您可以打印它并获得输出“endlines”。
First, you cannot write to argv[2]. (doing so produces behavior that is either implementation dependent or undefined. The distinction is unimportant: don't do it).
Second; where is the confusion? You probably have memory layed out with argv[2] immediately following argv[1], so it looks like "example/mountdir/location2.csv\0example/rootdir/location2.csv". argv[ 2 ] (path) points to the first 'e', and path2 points to the 'e' following the null byte. When you strcat to path, you are writing data starting at the \0, so the \0 gets replaced by '.', the 'e' gets replaced by the 'e' of endlines, etc, and now path2 points to the second character of the string '.endlines', so you print it and get output "endlines".