Reputation: 277
I'm trying to get a part of text in a file. I used "ifstream":
#include <fstream>
void func(){
char *myString;
ifstream infile;
infile.open("/proc/cpuinfo");
while (infile >> myString){
if (!strcmp(myString,"MHz"))
break;
}
}
and I get a "Segmentation fault". does anyone know why?
Upvotes: 1
Views: 12549
Reputation: 8587
char myString[256]
compiles fine just as well too.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void func()
{
char myString[256] ;
ifstream infile;
infile.open("/proc/cpuinfo");
while ( ! infile.eof() )
{
infile >> myString;
cout<<myString<<" \n";
if (! strcmp(myString,"MHz") )
{
infile.close();
break;
}
}
infile.close();
cout<<" \n";
}
int main()
{
func();
return 0;
}
Upvotes: 0
Reputation: 247999
There's a reason why C++ has a string class, you know. It's because using char pointers is cumbersome and error-prone.
infile >> myString
will read from the file into *wherever myString
points to. And it is an uninitialized pointer, it points to some random garbage address.
If you absolutely do want to use char pointers instead of strings, you'll have to allocate a buffer you can read data into.
But the sane solution is to replace it entirely by std::string
.
Upvotes: 1
Reputation: 31577
Because you did not allocate memory for myString
. The quick solution to this is to use std::string
instead of the C-style char*
strings, which does memory management so you don't have to.
Here's why your error occurs:
When you declare char *myString
you are creating a pointer to a character. However you do not initialize this pointer to anything, so it can point absolutely anywhere in memory. When you do infile >> myString
you are going to write a bunch of characters at an unspecified location in memory. It just so happens that this location was a vital part of your program, which caused it to crash.
Upvotes: 0
Reputation: 153919
Because the target value should be:
std::string myString;
and not char*
. It's possible to use char*
, but you have to ensure that it points to something big enough first. (In your case, it doesn't point anywhere—you forgot to initialize it.) And defining “big enough” is non-trivial, given that you don't know the size of the next word until you've read it.
Upvotes: 2
Reputation: 28951
You have not allocated memory for the myString
. Use std::string
. Or better any other language, python, perl, or unix utils such as grep, awk, sed.
Upvotes: 8