473,491 Members | 2,205 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Iterating over elements in a deque results in garbage.

Hey,

I am trying to insert a bunch of Token objects into a collection
called tokens of type deque<Token>. The problem is that the output of
Tokens::print is just junk. For instance, the call at the end of main
produces this output:

Value: fsdf
Width: 0

Value: dfwf
Width: 0

Value: sdfasd
Width: 0

The call to cout's insertion operation on the line after tokens.print
produces this output:

Value: test3
Width: 5

I can't figure it out. I suspect that it has something with variables
going out of scope, but I could use some help finding the problem.
Here is a simplified example:

#include <deque>
#include <iostream>
#include <cstring>
#include <cassert>

using namespace std;

class Token
{
const Token& operator=(const Token& r);
char value[255];
int width;

public:

Token(void) : width(0) { /*EMPTY*/ }

Token(const Token& t) {
strcpy(value, t.value);
width = t.width;
}

void append(const char c) {
value[width++] = c;
}

friend ostream& operator<<(ostream& os, const Token& token) {
os << "Value: " << token.value << endl
<< "Width: " << token.width << endl;

return os;
}
};

class Tokens
{
deque<Token> tokens;
Tokens(const Tokens&);

public:

Tokens(void) { /*EMPTY*/ }

Token* begin(void) {
return &*tokens.begin();
};

Token* end(void) {
return &*tokens.end();
};

void addNew(void) {
Token newToken;
this->tokens.push_back(newToken);
};

void Tokens::print(std::ostream& output = cout)
{
std::deque<Token>::iterator itr;

for (itr = tokens.begin() ; itr != tokens.end() ; itr++ )
output << " " << *itr << std::endl;
}
};

int main(int c, int v)
{
char* test[] = {"Test", "Test2", "test3"};
Tokens tokens;

for (int i = 0; i < 3; i++)
{
tokens.addNew();

for (int j = 0; j < strlen(test[i]); j++)
tokens.end()->append(test[i][j]);
}

tokens.print(); // This prints all of the tokens but they are rubbish.
cout << *tokens.end(); // This prints a test3 that isn't just junk.

return 0;
}

Thanks in advance.

--

Regards,

Travis Spencer
Portland, OR. USA
Jul 22 '05 #1
3 2270
"Travis L Spencer" <tr************@hotmail.com> wrote in message
news:sl*********************@jess.cs.pdx.edu...
I am trying to insert a bunch of Token objects into a collection
called tokens of type deque<Token>. The problem is that the output of
Tokens::print is just junk. Hi Travis... Just taking a quick read through: Token(const Token& t) {
strcpy(value, t.value);
width = t.width;
} Actually this class would be ok with the default copy
constructor (which would do a byte-wise copy of the array).
void append(const char c) {
value[width++] = c;
} Some overflow checking would be nice.

class Tokens .... Token* end(void) {
return &*tokens.end();
}; .... for (int j = 0; j < strlen(test[i]); j++)
tokens.end()->append(test[i][j]);

That's the problem: container.end() returns a one-past-the-end
element which shall not be dereferenced (e.g. like the a[5]
element of the variable int a[5] ).
What you want to use is the back() member function of
std::deque (or any other sequence container), which returns a
valid reference to the last element in a non-empty collection:
Token& back(void) {
return tokens.back();
};
....
for (int j = 0; j < strlen(test[i]); j++)
tokens.back().append(test[i][j]);
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #2

"Travis L Spencer" <tr************@hotmail.com> skrev i en meddelelse
news:sl*********************@jess.cs.pdx.edu...
Hey,

I am trying to insert a bunch of Token objects into a collection
called tokens of type deque<Token>. The problem is that the output of
Tokens::print is just junk. For instance, the call at the end of main
produces this output:

Value: fsdf
Width: 0

Value: dfwf
Width: 0

Value: sdfasd
Width: 0

The call to cout's insertion operation on the line after tokens.print
produces this output:

Value: test3
Width: 5

I can't figure it out. I suspect that it has something with variables
going out of scope, but I could use some help finding the problem.
Here is a simplified example:

#include <deque>
#include <iostream>
#include <cstring>
#include <cassert>

using namespace std;

class Token
{
const Token& operator=(const Token& r);
char value[255];
Looking at the rest of the code, this looks like a null-terminated C-string.
Instead, I'd recommend you use std::string - a much safer choice.
int width;

public:

Token(void) : width(0) { /*EMPTY*/ }
Here value is undefined - you will not be able to print it.
Have value[0] = 0;

Token(const Token& t) {
strcpy(value, t.value);
width = t.width;
}

void append(const char c) {
value[width++] = c;
Once again you destroy the null terminator needed if you are to print your
values out.

}

friend ostream& operator<<(ostream& os, const Token& token) {
os << "Value: " << token.value << endl
<< "Width: " << token.width << endl;

return os;
}
};

class Tokens
{
deque<Token> tokens;
Tokens(const Tokens&);

public:

Tokens(void) { /*EMPTY*/ }

Token* begin(void) {
return &*tokens.begin();
};

Token* end(void) {
return &*tokens.end();
};

void addNew(void) {
Token newToken;
this->tokens.push_back(newToken);
};

void Tokens::print(std::ostream& output = cout)
{
std::deque<Token>::iterator itr;

for (itr = tokens.begin() ; itr != tokens.end() ; itr++ )
output << " " << *itr << std::endl;
}
};

int main(int c, int v)
{
char* test[] = {"Test", "Test2", "test3"};
Tokens tokens;

for (int i = 0; i < 3; i++)
{
tokens.addNew();

for (int j = 0; j < strlen(test[i]); j++)
tokens.end()->append(test[i][j]); This loop looks horrible, but the worst thing is that you dereference end().
End points past any values, and you are not allowed to modify it.
}

tokens.print(); // This prints all of the tokens but they are rubbish.
cout << *tokens.end(); // This prints a test3 that isn't just junk.

return 0;
}

Thanks in advance.

--

Regards,

Travis Spencer
Portland, OR. USA


/Peter
Jul 22 '05 #3
On 2005-01-21, Peter Koch Larsen <pk*****@mailme.dk> wrote:
Token(void) : width(0) { /*EMPTY*/ }


Here value is undefined - you will not be able to print it.
Have value[0] = 0;


OK. I rewrote is like so:

Token(void) : width(0), value(0) { /*EMPTY*/ }
Token(const Token& t) {
strcpy(value, t.value);
width = t.width;
}

void append(const char c) {
value[width++] = c;


Once again you destroy the null terminator needed if you are to print your
values out.


Shoot. I changed the declaration to value[MAX_TOKEN_WIDTH + 1] and in
all constructors but the default one, I called bzero to insure that it
is zeroed out. I also made sure that I never overflow value.

Token {

char value[MAX_TOKEN_WIDTH + sizeof('\0')];
....

public:

Token(int w) : width(w)
{
bzero(value, MAX_TOKEN_WIDTH + sizeof('\0'))
}

void append(const char c)
{
if (width < MAX_TOKEN_WIDTH)
{
value[width++] = c; //
assert(value[width] == '\0');
}
}
....
};
int main(int c, int v)
{
char* test[] = {"Test", "Test2", "test3"};
Tokens tokens;

for (int i = 0; i < 3; i++)
{
tokens.addNew();

for (int j = 0; j < strlen(test[i]); j++)
tokens.end()->append(test[i][j]);

This loop looks horrible, but the worst thing is that you dereference end().
End points past any values, and you are not allowed to modify it.


Ya, the idea was just to make a stripped down demonstration. It isn't
what I'm actually using to populate the deque of tokens. But you're
right that the end function was the source of my problems. Thanks for
catching that.

--

Regards,

Travis Spencer
Portland, OR. USA
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1965
by: Stefan Behnel | last post by:
Hi! In Python 2.4b3, the deque is causing a segfault on two different machines I tested on. With deque, my program runs fine for a while (at least some tens of seconds up to minutes) and then...
8
2185
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in...
7
4443
by: jose luis fernandez diaz | last post by:
Hi, Is this right any stl container (vector, deque, list, . . .)? typedef vector container; int main() { container<int> c1;
34
4126
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and...
34
4128
by: Christopher Benson-Manica | last post by:
If an array is sparse, say something like var foo=; foo=4; foo='baz'; foo='moo'; is there a way to iterate through the entire array? --
9
3706
by: R.Z. | last post by:
i was wondering whether it pays off in terms of memory use to maintain lots of empty deques (it would be convenient for my algorithms but memory use is more important). and does the size of a deque...
5
12046
by: Alan | last post by:
I was wondering whether it is good programming practice or asking for trouble to modify a vector while iterating through it. That is, I want to do something like the following pseudocode in C++: ...
12
2613
by: arnuld | last post by:
It works fine. any advice on making it better or if I can improve my C++ coding skills: /* C++ Primer - 4/e * * Chapter 9 - Sequential Containers * exercise 9.18 - STATEMENT * ...
4
2802
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a...
0
7154
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7190
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6858
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5451
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4881
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3086
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1392
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
280
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.