use resize instead of substr and reassigning - #6517
Conversation
efeda8e to
b6a55cb
Compare
| if (shm_name.size() > SF_MAX_SEM_NAME_LEN) | ||
| { | ||
| shm_name = shm_name.substr(0, SF_MAX_SEM_NAME_LEN - 1); | ||
| shm_name.resize(SF_MAX_SEM_NAME_LEN - 1); |
There was a problem hiding this comment.
The change looks fine but looking at the code I would expect that we resize the string to a size of SF_MAX_SEM_NAME_LEN rather than SF_MAX_SEM_NAME_LEN - 1.
There was a problem hiding this comment.
This line does the same as the previous one.
Why did we use Edit: comments crossed with UniQP |
I'm not sure, but if you'd like I can modify it to use |
Please change it to |
b6a55cb to
04c79e8
Compare
|
i believe it was because we use c_str for the shm function calls and c_str is null terminated, so the actual amount of characters we can use is - 1 |
But then the check is wrong and needs to be changed to |
mhh that is true.. |
|
Wait, if we use |
|
the here the example code: #include <iostream>
#include <string>
#include <cstring>
#define MAX_LEN 5
int main()
{
std::string s = "123456789";
std::cout << "size is " << s.size() << '\n';
if (s.size() > MAX_LEN) {
s.resize(MAX_LEN);
}
std::cout << "now string is " << s << '\n';
std::cout << "and c_str returns " << s.c_str() << '\n';
std::cout << "and strlen returns " << strlen(s.c_str()) << '\n';
return 0;
}Its return: |
|
What should I do? |
this avoids unnecessary copying