Search code examples
cvisual-studiovisual-studio-2015strcpy

Visual Studio error: 'strcpy_s': too few arguments for call


I have run following C code in the Code::Blocks IDE and it worked properly without a problem. I tried compiling this code in Visual Studio 2015, and I got this error:

'strcpy_s': too few arguments for call

How can I fix this with minimal changes to my code? Here's the code:

#include<conio.h>
#include<stdio.h>
#include<string.h>
int main() {
    char string [81];
    int position;
    printf("type a string :");
    gets(string);
    printf("enter position for delete character :");
    scanf_s("%d", &position);
    strcpy_s(&string [position], &string [position + 1]);
    printf("the result string is: ");
    puts(string);
    _getch();
    return 0;
}

Code::Blocks can run this code and gives me the correct output, but Visual Studio does not! What can I do?


Solution

  • You are using strcpy_s, which is a specialized version of strcpy that does additional error checking and wants exactly 3 arguments:

    errno_t strcpy_s(char *dest, rsize_t dest_size, const char *src);
    

    I suppose you don't really need this. Use the standard strcpy function instead:

    strcpy(&string[position], &string[position + 1]);
    

    NOTE: same goes for scanf_s, use scanf instead if you don't have a good reason why scanf_s might be more useful to you.

    As per why Code::Blocks compiles your code, well, it's probably just generating a warning instead of an error that aborts compilation.


    Okay, turns out MSVC is particularly pedantic about this and doesn't like good ol' (faster and simpler) standard functions.

    I changed to strcpy but Visual studio gives me this error now: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

    You have two options:

    1. Disable the check, see this related question and answer: How to use _CRT_SECURE_NO_WARNINGS.

      Basically just add this at the very top of your file (before any #include):

      #define _CRT_SECURE_NO_WARNINGS
      
    2. Use strcpy_s in the proper way (also, check that position < strlen(string) first, otherwise your replacement is invalid):

      strcpy(&string[position], 81 - position, &string[position + 1]);
      

      And don't forget to check the return value!


    Finally, while we are at it, using gets(string) is ALWAYS wrong. Never use gets(). Really surprised MSVC does not warn you about this. Use fgets instead:

    fgets(string, 81, stdin);