Re: C++ dynamic structures
- From: "Doug" <DugzDC@xxxxxxxxxxxxxxxx>
- Date: 29 Aug 2006 09:14:34 -0700
googlinggoogler@xxxxxxxxxxx wrote:
Hi,
Im new to C++ and trying to self teach myself whilst I sit at my
unentertaining day job (thought i'd put that across before im accused
of cheating on my homework, im 45...)
Anyway I'm trying to dynamically assign a structure whilst I read from
a file, however my program crashes, and im not sure why other than that
its to do with my memory operations using new and delete.
Im pretty good at C so the reason for learning is so that I can truely
put C/C++ on my CV instead of just C... but also im interested in the
object orrientated aspect.
Could I use a class instead of a structure? whats best? where am I
going wrong?
Thanks
Heres my Code -
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TOKEN
{
string linetoken;
};
int main()
{
TOKEN *Tokens;
int counter = 0;
ifstream ifs("data.txt");
string line;
while(getline(ifs,line))
{
Tokens = new TOKEN[counter + 1];
Tokens[counter].linetoken = line;
//cout << "[ " << line << " ]" << endl;
cout << Tokens[counter].linetoken << endl;
counter = counter + 1;
}
cout << "AAAAAAAA";
delete Tokens;
return 0;
}
Hi there,
There are a couple of things here:
- your 'new' call is throwing away the old array of TOKENs each time
through the loop, so only your most recent token is ever valid.
- you need to 'delete []', not just 'delete'
However, I think the real reason for your crash is indeed using a
struct where you want to use a class. IIRC, I don't think that 'new'
calls the ctors of structs when it allocates them, whereas it does call
the ctor for classes. Hence, when you access .linetoken, you end up
accessing uninitialised garbage on the heap - causing you to fall over
shortly afterwards (probably chasing a garbage pointer within the
string object).
Just a guess - if I had more time I'd run it.
hth,
Doug
.
- Follow-Ups:
- Re: C++ dynamic structures
- From: Martin Eisenberg
- Re: C++ dynamic structures
- References:
- C++ dynamic structures
- From: googlinggoogler
- C++ dynamic structures
- Prev by Date: Re: Code Comprehension
- Next by Date: Java or C++ College Path
- Previous by thread: C++ dynamic structures
- Next by thread: Re: C++ dynamic structures
- Index(es):
Relevant Pages
|