测试代码:
#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);
}
问题解决了.