我将数据保存在两个不同的文件中,并使用strcat连接这些数据。奇怪的是,我最后一次调用strcat的结果会连接到我现在想要连接的两个字符串。可能有点模糊,下面是代码:
...
strcat(logline,"\n");
if(logging){
if(writeInFile(logfile,"a",logline))
printf(" Connection logged.");
else
printf(" Connection couldn't be logged.");
}
if(saving){
char* loc = (char*) malloc(BUFSIZ);
strcat(loc,client_ip);
strcat(loc,"-");
strcat(loc,server_ip);
strcat(loc,".txt");
if(writeInFile(loc,"a",request)){
printf(" Connection saved.");
}
else{
printf("ERROR: cannot create/open savefile %s\n",loc);
printf("Saving set to FALSE.");
saving = false;
}
}bool writeInFile(char* fileName, char* openingParam, char* content){
if(strcmp(openingParam,"a") == 0 || strcmp(openingParam,"w") == 0){
FILE* fptr = NULL;
fptr = fopen(fileName,openingParam);
if ( fptr == NULL)
{
printf("ERROR: cannot create/open logfile %s\n",fileName);
return false;
}
fprintf(fptr,"%s",content);
fclose(fptr);
return true;
}
return false;
}正在发生的情况是,日志行的内容放在loc的开头。所以创建了一个长得很长的文件。
编辑::文件应该命名为192.168.1.36-192.168.1.36.txt
但却被命名为
|--> timestamp = Sat Jan 2 20:09:24 2021
|--> remote = 192.168.1.36
|--> local = 192.168.1.36
|--> request = [timeout]
|--> END
192.168.1.36-192.168.1.36.txt|--> timestamp = Sat Jan 2 20:09:24 2021
|--> remote = 192.168.1.36
|--> local = 192.168.1.36
|--> request = [timeout]
|--> END是通过strcat获得的logline的值。
发布于 2021-01-02 19:37:34
strcat函数要求目标字符串实际上是一个正确的以空结尾的字符串。否则,它将导致未定义的行为。
您使用malloc分配的缓冲区不会以任何方式初始化。它绝对不是以空结尾的字符串。
您有四种可能的解决方案:
对于第一个调用,
strcpy而不是strcat:strcpy(loc,client_ip);
loc = '\0';//终止缓冲区,使其成为“空”字符串strcat(loc,client_ip);
calloc而不是malloc,因为这将使分配的内存为零,这与将其全部设置为字符串null-结束符相同:char* loc = calloc(BUFSIZ,1);
snprintf将字符串“打印”到未初始化的缓冲区中:snprintf(loc,BUFSIZ,"%s-%s.txt",client_ip,server_ip);
我个人推荐方法4,使用snprintf。
您的代码还有另一个问题:内存泄漏,因为您没有传递分配给free的内存。
要么在free(loc)超出作用域之前调用loc;要么让loc成为数组:
char loc[BUFSIZ];相反,使loc成为一个数组也意味着您可以轻松地初始化它:
char loc[BUFSIZ] = { '\0' };发布于 2021-01-02 19:46:14
Loc是未初始化的,strcat行为与uninit是未定义的,这就是问题所在。用strcpy代替strcat的第一次出现解决了它!
if(saving){
char* loc = (char*) malloc(BUFSIZ);
strcpy(loc,client_ip);
strcat(loc,"-");
strcat(loc,server_ip);
strcat(loc,".txt");
if(writeInFile(loc,"a",request)){
printf(" Connection saved.");
}
else{
printf("ERROR: cannot create/open savefile %s\n",loc);
printf("Saving set to FALSE.");
saving = false;
}
}https://stackoverflow.com/questions/65543227
复制相似问题