如果str在堆中申请的空间较小,使用scanf(“%s”,str)时,很容易发生溢出,怎么解决呢???
#include <stdio.h>
#include <malloc.h>
int main(int argc, char *argv[])
{
char *str = (char *)malloc(10 * sizeof(char));
printf("please input(10 at most):");
scanf("%s",str);
//scanf("%10s",str);
printf("\n");
printf("str: %s\n",str);
free(str);
return 0;
}
输出结果如下:
[centos7 at localhost Test1]$ gcc scanf.c -o scanf
[centos7 at localhost Test1]$ ./scanf
please input(10 at most):123456789
str: 123456789
[centos7 at localhost Test1]$ ./scanf
please input(10 at most):12345678901234567890
str: 12345678901234567890
[centos7 at localhost Test1]$
#include <stdio.h>
#include <malloc.h>
int main(int argc, char *argv[])
{
char *str = (char *)malloc(10 * sizeof(char));
printf("please input(10 at most):");
//scanf("%s",str);
scanf("%10s",str);
printf("\n");
printf("str: %s\n",str);
free(str);
return 0;
}
输出结果如下:
[centos7 at localhost Test1]$ gcc scanf.c -o scanf
[centos7 at localhost Test1]$ ./scanf
please input(10 at most):1234
str: 1234
[centos7 at localhost Test1]$ 1234567890
bash: 1234567890: command not found...
[centos7 at localhost Test1]$
总结:通过在scanf函数中添加个数控制,可以防止溢出的情况!!!
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
static char *
parse_version = "1.0.1";
static const struct option
long_opts[] = {
{"help", 0, 0, 'H'},
{"parse", 0, 0, 'p'},
{0,0,0,0}
};
static const char *
optstring = "Hp:";
static char *
parse_options[] = {
"--help -H Print the help informations\n",
"--parse -p Parse the message\n",
};
static void
help(void)
{
int index = 0;
printf("version: %s\n",parse_version);
for (index = 0; index < ARRAY_SIZE(parse_options); index++) {
printf("%s", parse_options[index]);
}
}
int
main(int argc, char* argv[]) {
int c = 0;
char *str = NULL;
while ((c = getopt_long(argc, argv,
optstring, long_opts, NULL)) != -1) {
switch (c) {
case 'H':
help();
return 0;
case 'p':
str = optarg;
break;
default:
help();
return -1;
}
}
if (str == NULL) {
printf("Error\n");
return -1;
}
//handler
printf("str: %s\n",str);
return 0;
}