Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
char*的printf获取分段错误_C_Segmentation Fault_Printf - Fatal编程技术网

char*的printf获取分段错误

char*的printf获取分段错误,c,segmentation-fault,printf,C,Segmentation Fault,Printf,我正在尝试从套接字读取数据,并使用printf打印到标准输出(必须) 然而,每次我从sane网站读取特定文件(HTML)时,我都会遇到分段错误 请看一下这个代码,告诉我出了什么问题 int total_read = 0; char* read_buff = malloc(BUF_SIZE); char* response_data = NULL; if (read_buff == NULL){ perror("malloc"); exit(1); } while((nbytes

我正在尝试从套接字读取数据,并使用printf打印到标准输出(必须)

然而,每次我从sane网站读取特定文件(HTML)时,我都会遇到分段错误

请看一下这个代码,告诉我出了什么问题

int total_read = 0;
 char* read_buff = malloc(BUF_SIZE);
 char* response_data = NULL;
 if (read_buff == NULL){
  perror("malloc");
  exit(1);
 }
 while((nbytes = read(fd, read_buff, BUF_SIZE)) > 0){
  int former_total = total_read;
  total_read += nbytes;
  response_data = realloc(response_data, total_read);
  memmove(response_data + former_total, read_buff, nbytes); //start writing at the end of spot before the increase.
 }
 if (nbytes < 0){
  perror("read");
  exit(1);
 }

 printf(response_data);
int-total\u-read=0;
char*read\u buff=malloc(BUF\u大小);
char*response_data=NULL;
if(read_buff==NULL){
佩罗尔(“马洛克”);
出口(1);
}
而((nbytes=read(fd,read_buff,BUF_SIZE))>0){
int-former\u-total=总读取量;
总读取+=N字节;
响应数据=realloc(响应数据,总读取);
memmove(response_data+former_total,read_buff,nbytes);//在增加前的spot末尾开始写入。
}
如果(n字节<0){
佩罗(“阅读”);
出口(1);
}
printf(响应数据);

谢谢。

响应\u数据
可能没有NUL(
'\0'
)终止,因此
printf
继续经过字符串的末尾。或者它可能包含
%
指令,但
printf
找不到进一步的参数

相反,告诉
printf
读取的距离,不要解释字符串中的任何
%
指令

printf("%.*s", total_read, response_data);

请注意,如果
response\u数据
包含嵌入式NUL,
printf
将停止在那里,即使
total\u read
更长。

response\u数据
中可能会出现什么?如果它包含printf格式字符(即,
%
后跟一个常用选项),
printf
将尝试访问一些未传递的参数,很可能出现分段错误。是否改为尝试放置
put


如果您必须使用printf,请执行
printf(“%s”,response\u data)
(NUL首先终止它)

我从您的帖子中了解到,响应是HTML数据。
因为它是文本,所以您尝试打印它。不要像使用printf那样使用它。
相反,请执行以下操作:

for(int i = 0; i < total_read; i++)
   putc(response_data[i],stdout);
for(int i=0;i
您应该单击答案旁边的复选标记形状图标来解决您的问题。数据中可能会有什么反应?如果它包含printf格式字符,printf将尝试访问一些未传递的参数。改为尝试放置?一个更正是:printf(“%s”,总读取,响应数据);(不要在星号前出现)。@Luis:只有当
响应\u数据
有一个嵌入NUL时才重要,
%*s
用空格填充,
%-*s
在另一侧用空格填充,而
%*s
根本不填充。取决于OP想要什么…但字符串格式的精度不是要打印的最大字符数?@Luis:噢,糟了。你是对的,我很惊讶你是第一个抓住它的人。谢谢:)谢谢,它很管用。你能解释一下为什么这个简单的方法让我犯了一个分割错误吗?谢谢,这很有效。我仍在考虑使用哪种形式。Putc仍然不是这样做的方式。您正在重新实现printf“%.s”的功能。