strcat eccentric behavior

China☆狼群 提交于 2020-01-04 04:21:07

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7078349/strcat-eccentric-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!