c-如何使用snprintf()复制或连接字符串,而不会出现分段错误和内存溢出



我是C程序的新手。我想从";txt文件名"至";s1";。但我不知道在";txt文件名"提前我设置了";txt文件名"'s的数组大小为100。实际上存储在txtFilename中的字符总是<100因此,我设置";s1〃's的数组大小也为100。

我的目标是我想从";txt文件名"其尺寸小于100至"100";s1〃;并在s1中添加一些字符,而不会出现警告、分段错误或内存溢出。我的目标是将s1的内存仅存储到它被连接或复制的字符的大小,即使我设置";s1〃;至100。(例如,如果最后的s1="abcde12345",即使我设置s1[100],我也希望将s1自动设置为11,以避免内存溢出。(

我根据以下内容编写了程序:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{   char s1[100]="";
char txtFilename[100];
char t[100];
char m[100];

strcpy(txtFilename, "File_data_checking_415464324_444543.");
snprintf(s1,sizeof(s1),"%scsv",txtFilename);
printf("%sn",s1);
strcpy(txtFilename,s1);
printf("%sn",txtFilename);
snprintf(t,sizeof(t),"%s_sfewf",s1);
printf("%sn",t);
return 0;
}

我收到了这个警告。我可以知道如何解决这个警告吗?

main.c: In function ‘main’:
main.c:19:31: warning: ‘csv’ directive output may be truncated writing 3 bytes into a region of size between 1 and 100 [-Wformat-truncation=]
19 |     snprintf(s1,sizeof(s1),"%scsv",txtFilename);
|                               ^~~
main.c:19:5: note: ‘snprintf’ output between 4 and 103 bytes into a destination of size 100
19 |     snprintf(s1,sizeof(s1),"%scsv",txtFilename);
|     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.c:23:29: warning: ‘_sfewf’ directive output may be truncated writing 6 bytes into a region of size between 1 and 100 [-Wformat-truncation=]
23 |     snprintf(t,sizeof(t),"%s_sfewf",s1);
|                             ^~~~~~
main.c:23:5: note: ‘snprintf’ output between 7 and 106 bytes into a destination of size 100
23 |     snprintf(t,sizeof(t),"%s_sfewf",s1);
|     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
File_data_checking_415464324_444543.csv
File_data_checking_415464324_444543.csv
File_data_checking_415464324_444543.csv_sfewf

可以使用指针而不是数组
调用snprintf一次以获取所需的大小
为指针分配内存,然后再次调用snprintf

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void)
{
char *s1=NULL;
char txtFilename[100];
strcpy(txtFilename,"File_data_checking_415464324_444543.");
int size = snprintf(NULL,0,"%scsv",txtFilename);
++size; // for terminating zero
if ( NULL != ( s1 = malloc ( size))) {
snprintf(s1,size,"%scsv",txtFilename);
strcpy(txtFilename,s1);
printf("%sn",txtFilename);
free ( s1);
}
else {
fprintf ( stderr, "problem mallocn");
return 1;
}
return 0;
}

有时您需要寻找替代解决方案。

#include <stdio.h>
#include <string.h>
int main( void ) {
char s1[ 128 ]; // big enough...
strcpy( s1, "File_data_checking_415464324_444543" );
strcat( s1, "." );
strcat( s1, "csv" );
printf( "%sn", s1 );
printf( "len = %zun", strlen( s1 ) );
printf( "sizeof(s1) = %zun", sizeof(s1) );
return 0; 
}

最新更新