473,549 Members | 2,455 Online
Bytes | Software Development & Data Engineering Community
+ 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<<(ostr eam& 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_ba ck(newToken);
};

void Tokens::print(s td::ostream& output = cout)
{
std::deque<Toke n>::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 2279
"Travis L Spencer" <tr************ @hotmail.com> wrote in message
news:sl******** *************@j ess.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().a ppend(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******** *************@j ess.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<<(ostr eam& 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_ba ck(newToken);
};

void Tokens::print(s td::ostream& output = cout)
{
std::deque<Toke n>::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
1976
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 suddenly segfaults. I'm sorry I can't tell exactly when, but I'm running an application that uses a few hundred deques where elements are...
8
2191
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 the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the...
7
4449
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
4132
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 "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want...
34
4148
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
3714
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 depends on the size of its members even if the deque is empty? is there at all a way to check out how much memory my deque occupies? i've read that...
5
12078
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++: for each element of the vector for each subsequent element of the vector if the belong together <some code to compare them> then merge the...
12
2628
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 * Write a program to copy elements from a list of "ints" * to 2 "deques". The list elements that are even should go into one deque * and even...
4
2808
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 great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the...
0
7542
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7736
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7982
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7500
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6066
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3494
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1961
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 we have to send another system
1
1079
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
783
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.