[英]Segmentation fault (core dumped) in fputs()
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(){
size_t size;
char *line;
FILE *pipe = fopen("/ftproot/fifo", "r");
if(pipe == NULL){
perror("Could not open pipe for reading");
return EXIT_FAILURE;
}
FILE *out = fopen("/ftproot/output", "w");
if(out == NULL){
perror("Could not open output file for writing");
return EXIT_FAILURE;
}
while (getline(&line, &size, pipe) > 0) {
cout << "<<" << line << ">>\n";
fputs(line, out);
}
return 0;
}
原来,如果我删除行cout << "<<" << line << ">>\\n";
我收到细分错误。 但是,如果此行在代码内,则一切正常。
我不知道这怎么可能。 我将不胜感激。
提前致谢。
您尚未将行设置为NULL。 普通的局部变量最初在其中包含垃圾。
那么,为什么在打印行时它起作用? 变量中的“垃圾”恰好是变量存储在内存中的位置,并且取决于代码的其他作用,它可以更改。 这就是C ++标准所谓的“未定义的行为”,这意味着任何事情都可能发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.