strcpy_s - Buffer is too small && 0

Hi guys,
I have no idea what the strcpy_s function complains about...

1
2
3
4
5
6
7
8
9
10
11
12
  template<class V>
	bool get(std::string&  key, V& val, const MDB_cursor_op op)
	{
		char arrKey[256 + 1];
		int sizeofKey = key.size() -1;

		if (key.size() > 256)
			return false;

		strcpy_s(arrKey, sizeofKey, key.c_str());

		arrKey[sizeofKey + 1] = '\0'; // append terminator 
The second parameter to strcpy_s() is the size of the destination array ("arrKey"). You have passed in one less than the length of the key string instead.

You may be doing more work than needed, though. The c_str() method already gives you effectively a pointer to an array of characters; why do you need a separate mutable array?
Why are you even playing with the character array?

Why not just stick with the std::string?

closed account (E0p9LyTq)
strcpy_s is a Microsoft/Windows only version of the standard C library strcpy function.

If you have to use C-style strings why not use the StrSafe functions instead?
https://msdn.microsoft.com/en-us/library/windows/desktop/ms647465(v=vs.85).aspx
You may be doing more work than needed, though. The c_str() method already gives you effectively a pointer to an array of characters; why do you need a separate mutable array?


Why not just stick with the std::string?


Thanks that solved my problem, I did not mention the reason for not using .c_str() or just a string is that the next function retrieves the data and populates the variables: it also takes type void* :
full code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

	template<class V>
	bool get(std::string&  key, V& val, const MDB_cursor_op op)
	{
		char arrKey[256 + 1];
		int sizeofKey = key.size();

		if (key.size() > 256)
			return false;

		strcpy_s(arrKey, 257, key.c_str());

		arrKey[sizeofKey + 1] = '\0'; // append terminator

		MDB_val k{ sizeofKey, arrKey };
		MDB_val v{ sizeof(V), &val };

		bool gotData = lmdb::cursor_get(handle(), &k, &v, op); // this function populates key and value
		if (gotData)
		{
			char * someData = reinterpret_cast<char*>(k.mv_data);
			key = std::string(someData, k.mv_size);
			val = (*reinterpret_cast<V*>(v.mv_data));
		}

		return gotData;
	}


I don`t know if I could just
void * pKey = const_cast<void*>( reinterpret_cast<const void*>(key.c_str()));
and then
MDB_val k{ sizeofKey, pKey };
MDB_val v{ sizeof(V), &val };
lmdb::cursor_get(handle(), &key, &v, op);

Because I am worried that populating an object which use to be const will cause undefined behavior
Topic archived. No new replies allowed.