5
GCC10对sprintf的一个严格检查的修正方法.
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.
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);
}
问题解决了.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK