[英]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.