Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this problem with the gets_s function. This is my code snippet:
C++
char *string;
	int n;
	printf("Enter the max length:\n");
	scanf_s("%d",&n);
	printf("Enter the string:\n");
	gets_s(string);
	printf("%s",string);

The Errors I've been facing is this:
error C2660:'gets_s':function does not take 1 arguments
IntelliSense: no instance of overloaded function "gets_s" matches the argument list argument types are: (char *)


However, if I statically allocate
char string[ARRAY];(with a macro defined for size as ARRAY) I havent been facing any problem. I want the end user to define its own size. Someone please help me out!
Posted
Updated 7-Mar-13 6:00am
v2
Comments
[no name] 7-Mar-13 12:04pm    
http://msdn.microsoft.com/en-us/library/5b5x9wc7%28v=vs.80%29.aspx

gets_s does not take a single parameter - it takes two: http://en.cppreference.com/w/c/io/gets[^] You need to supply a size as well as a buffer.

However, since the code you show does not allocate any memory to the string parameter all you will do is pass in a null pointer and your application will immediately crash! :laugh:

Try using the malloc function to allocate some space - but don't forget to free it when you are finished with it!
 
Share this answer
 
gets() vs gets_s()

gets_s() is part of the new C11 standard and the replacement of the old gets(), but is safer. You can use gets() but you will then get a warning encouraging you to switch to gets_s(). As opposed to gets() that doesn't perform bounds checking, gets_s() restrict the length

What makes gets_s() safer?
gets_s() requires you to add another parameter which is the maximum size of the expected input to prevent access violation due to endless strings (without 'null' in their end),
 
Share this answer
 
The difference between gets() and gets_s() is that gets() writes characters out to an array that you provide and trusts that you have enough room, while gets_s() does a check for length before writing. For the following:

C++
char* array1 = new char[20];
gets_s(array1);  /* error */

char array2[20];
gets_s(array2);


The compiler can determine (at compile time) that array2 is of size 20, but can not do the same for array1. Whenever you pass a pointer to gets_s(), you also need to pass its length for the code to compile.

See the Microsoft documentation here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900