[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Basic, but what the hell am I doing wrong here?



On Fri, 2004-06-11 at 14:49, Kevin Mark wrote:
> On Thu, Jun 10, 2004 at 09:36:04PM -0400, Stephen Touset wrote:
> > I've opened and read files hundreds of times in my life. What gives now?
> > 
> > -- 
> > Stephen Touset <stephen@touset.org>
> 
> > #include <fstream>
> > 
> > using namespace std;
> > 
> > int main(void)
> > {
> > 
> > 	ifstream fin("test.cc");
> > 	char* str;
> > 
> > 	if (!fin.is_open())
> > 	{
> > 		exit(1);
> > 	}
> > 
> > 	while (!fin.eof())
> > 	{
> > 		fin.getline(str, 80);
> > 	}
> > 
> > 	fin.close();
> > 
> > 	return 0;
> > 
> > }
> Hi Stephen,
> I can understand your confusion. you have a perception issue that is
> clouding your understanding. either that or you have been looking at
> this for umteen hours and too much caffine x-). The issue is the
> understading of memory allocation versus pointer definition.
> 
> 'char * str' defines a 'char *' called str. it allocates memory for this
> pointer. so, str has an address of 0xabcd (for example). It has not been
> initialized with anything, so it contains undeterminate data (eg.
> garbage). lets say it the contents of address 0xabcd is 'Z'. so, *str =
> 'Z'. What does *(str + 1) contain? undeterminate data. As does *(str +
> 2) ... *(str + 79). So you define str, don't initialize it and then read
> data into *(str) ... *(str + 79). Well not really, becase you have no
> right to write to those areas. Why? because you have not allocate memory
> at those addresses. How do you do this? well in c you'd 'malloc. But
> this is c++, so, you'd use 'new', I think.

Yep. or:
  char str[80];

And in c++, there probably is a way to read directly into a string or
stringstream object or similar, which is much safer (and easier) than
calling malloc or new.

(damn; it's been about 5 years since I last seriously used c++ and it's
all forgotten...)

Regards,

Simon



Reply to: