gpt4 book ai didi

c - 记录 c 有时会给出 segafult

转载 作者:行者123 更新时间:2023-11-30 17:41:40 25 4
gpt4 key购买 nike

正在我的应用程序中创建日志文件。应用程序将数据写入日志文件,并在大小达到 10 MB 时进行轮换(旧的删除,新的添加)。

This works fine ,but sometime it gives segafult.
The code for the same

/* when the application starts the new file got created on the path*/
char path[1024];
char logpath[1024];
char logfile_name[20] = "test";
getcwd(path,1024);
sprintf(logpath,"%s/TEST_LOGS/%s_%d_%d.log",path,logfile_name,
app_inst_id,getpid());
/
logfptr = fopen(logpath,"a");
if(logfptr == NULL)
{
printf("log file open failed\n");
exit(0);
}

最初创建的日志文件

int vlr_write_log(const char *format, va_list A)
{
struct stat st;
char path[1024];
char logpath[1024];
char logfile_name[20] = "test";
getcwd(path,1024);
sprintf(logpath,"%s/TEST_LOGS/%s_%d_%d.log",path,logfile_name,
app_inst_id,getpid());
int size_in_byte = 10*1024*1024;
if (logfptr!=NULL)
{
if( stat(logpath,&st) == 0)
{
/******* if file size is less than 10MB
append it to the log file also
open it in write mode *******/

if( st.st_size < size_in_byte)
{
vfprintf(logfptr,format,A);
}
else
{
fflush(logfptr);
if(logfptr!= NULL)
fclose(logfptr); // this gives the error
logfptr = NULL;
logfptr = fopen(logpath,"w");
vfprintf(logfptr,format,A);
}
}
else
{
if(logfptr!= NULL)
fclose(logfptr);
logfptr = NULL;
logfptr = fopen(logpath,"w");
vfprintf(logfptr, format, A);
fflush(logfptr);
}
}

return 0;
}

以及相同的回溯

#0  0xffffe410 in __kernel_vsyscall ()
#1 0x0036fe30 in raise () from /lib/libc.so.6
#2 0x00371741 in abort () from /lib/libc.so.6
#3 0x003a88cb in __libc_message () from /lib/libc.so.6
#4 0x003b0c65 in _int_free () from /lib/libc.so.6
#5 0x003b4c59 in free () from /lib/libc.so.6
#6 0x0039f2d6 in fclose@@GLIBC_2.1 () from /lib/libc.so.6
#7 0x08049aa7 in vlr_write_log (format=0xff99525c "[2014-01-10 17:06:13.416] key = input_list:LM1561171389353710\n", A=0xff995374 "\340\\\231\377 \004"

)

谢谢萨罗杰

最佳答案

从堆栈跟踪中,您显然已经覆盖了堆上的某些内容。具体内容和位置尚不清楚,但它不会立即出现在您的日志记录代码中,因为它不会访问堆。 (尽管考虑到你一刀切的缩进,这是相当困难的)。

顺便说一句,这个:

char path[1024];
char logpath[1024];
getcwd(path,1024);
sprintf(logpath,"%s/TEST_LOGS/%s_%d_%d.log",path,logfile_name,app_inst_id,getpid());

可以更安全地编码为:

char path[1024];
char logpath[1024];
getcwd(path, sizeof(path));
snprintf(logpath, sizeof(logpath), "%s/TEST_LOGS/%s_%d_%d.log", path, logfile_name, app_inst_id, getpid());

如果你的路径有点大,你真的应该测试 getcwd 和 snprintf 的返回码

关于c - 记录 c 有时会给出 segafult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21043841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com