dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: strcpy_s

  1. #1
    Join Date
    Dec 2007
    Location
    France
    Posts
    320

    strcpy_s

    Hello!

    Im trying to compile this simple example with strcpy_s and getting

    `strcpy_s' was not declared in this scope error.

    If i use the "old" strcpy, it works. Using CodeBlocks with mingw.

    Code:
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    
    int main( void )
    {
       char string[80];
       // using template versions of strcpy_s and strcat_s:
       strcpy_s( string, "Hello world from " );
       strcat_s( string, "strcpy_s " );
       strcat_s( string, "and " );
       // of course we can supply the size explicitly if we want to:
       strcat_s( string, _countof(string), "strcat_s!" );
    
       printf( "String = %s\n", string );
    }

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,559

    Re: strcpy_s

    Not that it helps you much, but it compiles clean with VC 2005

  3. #3
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: strcpy_s

    I believe the "safe" versions of C library functions (the ones ending in _s) are a Microsoft extension. They are not present in the standard C library, so you can only use them if you use Microsoft's compilers (Visual C++/Visual Studio).

    If you're concerned about the safety of string functions, and you're using C++, I'd strongly recommend taking a look at the std::string class and using that instead of the C string functions.
    Old Unix programmers never die, they just mv to /dev/null

  4. #4
    Join Date
    Dec 2007
    Location
    France
    Posts
    320

    Re: strcpy_s

    Thank you very much for both of you!

  5. #5
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: strcpy_s

    There's almost no reason to prefer strcpy_s over strncpy. Both limit the number of characters written to the buffer size. The latter doesn't guarantee to NULL-terminate the buffer, so just make sure to strncpy with a limit of 1 byte fewer than you actually have, and then set the last byte to 0 to be on the safe side.

    Of course, as stated std::string is preferred, not to mention much easier.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)