字符串格式在 fprintf 中有效,但在 sprintf 中不起作用,出现分段错误
fprintf(fp,"IP: %d: %.*s\n",
ip,
strstr(strstr(p->data, "User-Agent:"),"\n") - strstr(p->data, "User-Agent:"),
strstr(p->data, "User-Agent: ") );
fclose(fp);
大家好,正如您所看到的,在上面的语句中,我试图从包含整个 http 数据包数据的 char 指针中注销用户代理标头。问题是,在摆弄字符串格式之后,我想出了这个 %.*s 格式,它可以让我动态选择要打印到文件的字符数,然后打印它们。代码基本上所做的是,首先,它打印一个 int,然后传递从“User-Agent:”出现到下一个出现的换行符的字符数,然后传递该数量的字符在“User-Agent:”开始的地方,从整个数据包数据字符串开始。我知道这一切都很混乱,但工作得很好。但它在 sprintf 中不起作用。
请保存我所有的硬话!任何帮助表示赞赏!
char *stat;
sprintf(stat,"%.*s\0",
strstr(strstr(p->data, "User-Agent:"),"\n") - strstr(p->data, "User-Agent:"),
strstr(p->data, "User-Agent: ")) ;
fprintf(fp,"IP: %d: %.*s\n",
ip,
strstr(strstr(p->data, "User-Agent:"),"\n") - strstr(p->data, "User-Agent:"),
strstr(p->data, "User-Agent: ") );
fclose(fp);
Hi All, as you can see, in the above statement, I am trying to write off just the User Agent header from a char pointer which contains the entire http packet data. The thing is, After fiddling with the string format, I came up with this %.*s format which lets me, dynamically select the number of characters to be printed to the file, and then prints them. What the code is basically doing is, first, it's printing an int, then the number of chars from the occurrence of "User-Agent:" to the very next occurrence new line character is passed, and that amount of chars are then passes starting at where the "User-Agent:" starts, from the entire packet data string. I know it's all pretty messy, but it's working fine. Except that it's not working in sprintf.
Please save all my hard word! Any help is appreciated!
char *stat;
sprintf(stat,"%.*s\0",
strstr(strstr(p->data, "User-Agent:"),"\n") - strstr(p->data, "User-Agent:"),
strstr(p->data, "User-Agent: ")) ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有为
stat
分配内存。尝试You are not allocating memory for
stat
. Try当您使用 sprintf 时,您需要写入一个字符数组。您正在写入未初始化的指针。
试试这个:
When you use sprintf, you need an array of characters to write into. You're writing to an uninitialized pointer.
Try this instead:
好吧,您正在尝试将数据写入未初始化的未分配的随机内存位置。现在这不可能行得通了。
要么执行:
要么:
并确保“SUFFICIENTLY_LARGE_NUMBER”有足够的字节来容纳字符串,并且没有不必要的大。
PS:snprintf,因为你的格式不包括长度限制。如果是这样,
sprintf
就可以,但切勿将sprintf
与无限的%s
一起使用。您的%.*s
虽然受到形式上的限制,但还不够,因为表达式很乐意返回超过分配的缓冲区大小的内容,因此您需要另一次检查以避免溢出。Well, you are trying to write the data into uninitialized unallocated random memory location. Now that can't possibly work.
Either do:
or:
and make sure "SUFFICIENTLY_LARGE_NUMBER" is enough bytes that the string fits in and not unnecessarily huge.
PS: snprintf, because your format does not include length limits. If it does,
sprintf
is OK, but never ever usesprintf
with unlimited%s
. Your%.*s
, while formally limited, is not enough, because the expression will happily return more than the size of the allocated buffer, so you need another check to avoid overruning it.