Strlcat Problem: why strlcat does not work?

HI,

I come across a strange problem when using strlcat, as follows:

static int get_path(char *parent, char * file){
int parent_len = strlen(parent);
int file_len = strlen(file);
if(parent_len + file_len > 256) {
return 0;
}
int ret = strlcat(parent, file, file_len);
}

int main(int argc, char *argv[]) {
char path[256];
char file[256];
snprintf(path, 256, "%s", "./parent/");
snprintf(file, 256, "%s", "test.dat");
get_path(path, file);
cout << path << endl;
cout.flush();
}

The output is :

./parent/


The problem is why the output is "./parent/"? Is it supposed to be "./parent/test.dat"?

Thanks
Xiong
The problem is that you are trying to program C in C++. Use std::string instead, then you won't have stupid problems like this.
And you should call strlcat with the length of the size of the dest buffer, not the with length of src+dest. So you should pass 256 there.
Last edited on
Clarification: the problem is not that you are using C instead of C++. The problem is that the 3rd parameter to strlcat is the total length of your buffer.

This parameter prevents strlcat from writing over adjoining memory by overflowing your variable's bounds. It thinks your buffer is too small to combine both, so it doesn't do anything to the original. Hence, nothing changed.

So changing from
int ret = strlcat(parent, file, file_len);
to
return strlcat(parent, file, 256);
will fix your problem.

I hope this helps.
Last edited on
That's what I said starting in the second paragraph. And that he writes C-style code in C++ IS a problem.
Topic archived. No new replies allowed.