Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy_s not working with gcc

I have a C++11 project, and I added some strcpy_s method calls. This works on windows, but when compiling on gcc, there is an error stating that strcpy_s symbol is not found.

I did add the line

#define __STDC_WANT_LIB_EXT1__ 1

to the code, to no avail.

like image 871
Jacko Avatar asked Oct 14 '16 14:10

Jacko


People also ask

Does gcc support strcpy_ s?

GCC (or rather, glibc) does not support strcpy_s() and friends. For some ideas on where you can find a library which does support them, see here: Are there any free implementations of strcpy_s and/or TR24731-1? Save this answer.

What is the difference between strcpy and strcpy_s?

When you try to copy a string using strcpy() to a buffer which is not large enough to contain it, it will cause a buffer overflow. strcpy_s() is a security enhanced version of strcpy() . With strcpy_s you can specify the size of the destination buffer to avoid buffer overflows during copies.

How does strcpy_s work in C++?

1) Copies the null-terminated byte string pointed to by src , including the null terminator, to the character array whose first element is pointed to by dest . The behavior is undefined if the dest array is not large enough. The behavior is undefined if the strings overlap.

Where is strcpy_s defined?

The strcpy_s() and strcat_s() functions are defined in ISO/IEC TR 24731 as a close replacement for strcpy() and strcat(). These functions have an additional argument that specifies the maximum size of the destination and also include a return value that indicates whether the operation was successful.


2 Answers

GCC (or rather, glibc) does not support strcpy_s() and friends. For some ideas on where you can find a library which does support them, see here: Are there any free implementations of strcpy_s and/or TR24731-1?

like image 130
John Zwinck Avatar answered Oct 02 '22 13:10

John Zwinck


strcpy_s and friends are not a part of C++ just yet. It seems that C++17 will have them, but as of now providing them is up to the implementations. It seems glibc doesn't.

In fact, according to the cppreference, __STDC_WANT_LIB_EXT1__ will only work if __STDC_LIB_EXT1__ is defined. On my Arch Linux it isn't.

#ifdef __STDC_LIB_EXT1__
constexpr bool can_have_strcpy_s = true;
#else
constexpr bool can_have_strcpy_s = false;
#endif

You can use strncpy. With some care, it can be safe.

like image 30
krzaq Avatar answered Oct 02 '22 14:10

krzaq