5

GCC10对sprintf的一个严格检查的修正方法.

 2 years ago
source link: https://www.taterli.com/8353/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

GCC10对sprintf的一个严格检查的修正方法.

  • TaterLi
  • 2021年11月10日2021年11月10日

测试代码:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main(){
    char *buf;
    buf = (char *)malloc(1000);
    for(uint8_t i = 0;i < 10;i++){
        sprintf(buf, "%s:%d\n", buf, i);
    }
    printf("%s",buf);
}

使用严格的编译:

gcc -Wall -Werror 1.c

得到错误:

1.c: In function ‘main’:
1.c:9:9: error: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Werror=restrict]
    9 |         sprintf(buf, "%s:%d\n", buf, i);
      |         ^~~~~~~
cc1: all warnings being treated as errors

当然也有可能得到类似如下错误.

argument 3 overlaps destination object

主要是因为套娃,那么就把套娃的事情外置.

int main(){
    char *buf;
    buf = (char *)malloc(1000);
    size_t extra_len = strlen(buf);
    for(uint8_t i = 0;i < 10;i++){
       extra_len += sprintf(buf+extra_len, ":%d\n", i);
    }
    printf("%s",buf);
}

问题解决了.

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论

显示名称 *

电子邮箱地址 *

网站地址


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK