strcat() appending chunk data

For some reason when i use strcat() it append additional "/" to buffer where i'm trying to store other two chars. Code under gives me result "/raw/TbhaeQGm" instead of "raw/TbhaeQGm". Maybe im wrongly relocating size for buffer2 ?

1
2
3
4
5
6
7
8
9
10
  	const char* b = "raw";
	const char* c = "/";
	const char* d = "TbhaeQGm";

	char* buffer2 = new char[(strlen(b) + strlen(c) + strlen(d))];
	strcat(buffer2, b);
	strcat(buffer2, c);
	strcat(buffer2, d);

	MessageBox(NULL, buffer2, "OK", MB_OK);
It looks like you're not leaving enough room for the end of string character. But why are you using error prone C-strings instead of using the much safer std::string?

1
2
3
4
5
6
7
8
9
  	const std::string b = "raw";
	const std::string c = "/";
	const std::string d = "TbhaeQGm";

	std::string buffer2 = b + c + d;
	
	MessageBox(NULL, buffer2.c_str(), "OK", MB_OK);

	


And don't forget to use more meaningful variable names as well.

Last edited on
In addition to using a buffer that is too small, line 5 leaves the memory pointed to by buffer2 uninitialized. It's supposed to be an empty C-string, but that isn't guaranteed.

Make the buffer big enough, and fill it with zeros, so that it represents an empty C-string:
 
char* buffer2 = new char[(strlen(b) + strlen(c) + strlen(d)) + 1] {};

Or, instead of initializing, use strcpy on line 5.
Last edited on
Topic archived. No new replies allowed.