我有以下代码:
#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";,就会收到分段错误。但是,如果这一行在代码中,一切都可以正常工作。
我不知道这怎么可能。如果有任何答复我将不胜感激。
提前谢谢。
发布于 2015-01-12 11:32:23
您还没有将行设置为空。普通局部变量最初在它们中有垃圾。
那么,当你打印这条线时,它为什么会起作用呢?变量中的“垃圾”恰好发生在存储变量的内存中,并且取决于您的代码所做的其他操作,它可以更改。这就是C++标准所说的“未定义的行为”,这意味着任何事情都可能发生。
https://stackoverflow.com/questions/27900726
复制相似问题