scanf的溢出控制与替代使用

如果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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值