0

I am trying to concatenate root and absolute path for pset6 but i get extra characters at the start of it but am not sure why.

This is my code:

// concatenate root and absolute-path
char path[strlen(root)+strlen(rqTarget)];
     strcat(path,root);
     strcat(path,rqTarget);

// ensure path exists
if(access(path, F_OK) !=0 )
{
    printf("%s\n",root);
    printf("%s\n",rqTarget);
    printf("%s\n",path);
    error(404);
    continue;
}

Terminal window shows this data:

/home/jharvard/Dropbox/pset6/public
/hello.html
��/home/jharvard/Dropbox/pset6/public/hello.html
HTTP/1.1 404 Not Found

I do not understand why i get these extra characters at the start of the path variable.

Please help.

1
  • Perfect answer, curiouskiwi. After also running into this problem I was so happy with your answer, just so easy !
    – user9514
    Sep 9, 2015 at 7:31

1 Answer 1

1

You will get whatever garbage happens to be in path since it has not been initialised. You then are concatenating to that garbage.

Let's say that path had 'X' 'X' '0' 'X' etc... When strcat runs, it will look for the end of the existing string (which is where it finds the 0) and put root there. So you end up with "XXroot".

Instead, change that first strcat to a strcpy and it will replace XX0X with "path0".

2
  • So what is the computer doing when i use strcat the first time with root, so i understand on a technical level?
    – user7869
    Aug 22, 2015 at 0:32
  • It's doing exactly what you told it to do. It's concatenating "root" onto "path" (i.e., it's putting "root" at the end of "path", where it found the null terminator.) So if path had 2 bytes of garbage and then a 0 byte, then strcat would put root after those 2 bytes. (added to answer)
    – curiouskiwi
    Aug 22, 2015 at 0:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .