-1

i am trying to use struct to make some kind of list that takes the student's name, number etc. My problem when i try to build solution and see if there is an error, compiler(Visual Studio 2013) tells me to use "strcpy_s" intead of "strcpy". And when i fix it this time i get errors related to string string sizes. What exactly am i doing wrong?

#include <stdio.h>
#include<string.h>

struct student
{
char name[20];
char surname[20];
char dep[50];
int Class;
int num;
}stud;

main(void){
strcpy(stud.name, "goktug");
strcpy(stud.surname, "saray");
strcpy(stud.dep, "elektrik");

}
simonJarr
  • 28
  • 7
  • 1
    Possible duplicate of [Difference between 'strcpy' and 'strcpy\_s'?](https://stackoverflow.com/questions/32136185/difference-between-strcpy-and-strcpy-s) – Evan Weissburg Dec 25 '17 at 20:15
  • I suspect you're not providing enough arguments (size of the destination buffer) to `strcpy_s`. Take a look [here](https://social.msdn.microsoft.com/Forums/en-US/a85eb0a4-759c-4dc9-9678-c569facb664d/strcpy-vs-strcpys?forum=vcmfcatl) – yano Dec 25 '17 at 20:18
  • 4
    don't listen to MSVC warnings about strcpy. Strcpy is fine. – Jean-François Fabre Dec 25 '17 at 20:19
  • @Jean-FrançoisFabre.: Would you clarify? – user2736738 Dec 25 '17 at 20:22
  • 2
    Microsoft goes its own way. At first I went along with their "better" functions, but now I defeat them with these `#define`s added before any `#include` statements. `#define _CRT_SECURE_NO_WARNINGS \ #define _CRT_SECURE_NO_DEPRECATE \ #define _CRT_NONSTDC_NO_DEPRECATE` and use the standard C functions. – Weather Vane Dec 25 '17 at 20:34
  • 1
    you can use `sprintf(stud.name,"%19s",other);` that's standard _and_ safe. – Jean-François Fabre Dec 25 '17 at 20:51
  • Possible duplicate of [How to use \_CRT\_SECURE\_NO\_WARNINGS](https://stackoverflow.com/questions/22450423/how-to-use-crt-secure-no-warnings) – Bo Persson Dec 26 '17 at 09:42

1 Answers1

3

Well safe unsafe question is coming because of the buffer over run issue. strcpy is not aware of destinations characeter holding capability. That's why its unsafe.

Safer would be strcpy_s( stud.name, 20, "goktug" );. Here we are specifying that no matter what we should be in limit of 20 as destnation is capable of holding 20 characters including the NUL terminating character.

One can argue that here data is being truncated which is not better than a clear message that destination is too small to hold the copied thing, but surely better than a buffer overrun exploits. If we think along that line then well, we can reach the conclusion that we shouldn't call them unless we become sure that destination can hold the copied string.

user2736738
  • 30,591
  • 5
  • 42
  • 56