#include <stdio.h>
#include <malloc.h>
int main(){
char *str= (char *)malloc(20*sizeof(char));
scanf_s("%s", str);
printf("%s\n",str);
}
在使用VS2017时,应编译器要求需使用更加安全的scanf_s代替scanf,然而习惯scanf的语法后老是被这个scanf_s坑,特别是在写入字符串数组或者其它数组时经常会被坑,如上如所示。上述代码编译器不会报错,但调试时却出现图片中的异常,原因却是scanf_s在使用数组指针作为写入变量地址参数时,还需要加一个buffer长度参数,更安全(C程序员随时都要考虑内存溢出问题)如下所示:
#include <stdio.h>
#include <malloc.h>
int main(){
char *str= (char *)malloc(20*sizeof(char));
scanf_s("%s", str,20);
printf("%s\n",str);
}
现在就可以愉快地使用scanf_s了!
特别注意在使用scanf_s时,buffersize参数