While using proc/mysql for c++ I have taken string as user input and converted into char via strcpy(c,s.c_str());
function, where c
is the binding variable through which I'll add value in the database table and s
is the string (user input), it is working fine but my teacher is asking me append '\0'
at the end - I can't understand the reason why I need to?
Your teacher is deluded.
c_str()
in itself appends a zero [or rather, std::string
reserves space for an extra character when creating the string, and makes sure this is zero at least at the point of c_str()
returning - in C++11, it is guaranteed that there is an extra character space filled with zero at the end of the string, always].
You DO need a zero at the end of a string to mark the end of the string in a C-style string, such as those used by strcpy
.
[As others have pointed out, you should also check that the string fits before copying, and I would suggest reject if it won't fit, as truncating it will lead to other problems - as well as checking that there isn't any sql-injection attacks and a multitude of other things required for "good pracice in an SQL environment"]
While the teacher is deluded on the appending '\0' to the string, your code exhibits another very bad bug.
You should never use strcpy in such a fashion. You should always use some routine which controls the nubmer of characters copied, like strncpy()
, or other alternatives, and provide it with the size of receiving variable. Otherwise you are just asking for troubles.
Just guessing, it's a protection against buffer overflow. If c
is only N
bytes long and s.c_str()
returns a pointer to a N+k
length string, you'd write k
bytes after c
, which is bad.
Now let's say (if you didn't SEGFAULT already) you pass this c
NUL-terminated string to a C function, you have no guarantee that the \0
you wrote after c
is still there. This C function will then read an undefined amount of bytes after c
, which is badder worse.
Anyway, use ::strncpy()
:
char c[64];
::strncpy(c, s.c_str(), sizeof(c));
c[sizeof(c)-1] = '\0';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.