开发者

strcat eccentric behavior

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 m开发者_开发问答odified 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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜