473,804 Members | 4,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Garbage in the 0th element of a char* array

Hello.

I have the following code, to do a simple operation by copying the elements
of a vector of strings into an array of char pointers. However, when I run
this code, the first element in the char array strarr[0] holds garbage
characters. For some reason, every time the strcpy function is called to
copy the string in temp to the array, it fills the 0th element in the strarr
array with garbage characters. Can someone try to compile this code and
debug it and see if they get the same results that I'm getting? Any insight
into why this might be happening? I'm really stumpped. The code works for
every other element in strarr except for the 0th element. I've even tried
directly setting the strarr[0]th element to the pointer of temp with this
statement:

strarr[i] = temp; // where i = 0

and the pointer value gets set, but the characters are still garbage. When
I look at the value of strarr[0] in the debugger, no matter how I assign the
temp string to the array index, it always comes out as garbage, even when
the pointer is equal to the value of temp. The temp variable holds the
correct string, but for some reason, it won't properly copy into the 0th
element of the array.

Any help on this would be greatly appreciated.

Thanks -

#include <iostream>
#include <string>
#include <vector>
#include <bitset>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
vector<string> str;
string s;
while(cin >> s)
str.push_back(s );
const size_t array_size = 100;
char *strarr[array_size];
int i = 0;
for(vector<stri ng>::iterator iter = str.begin();ite r !=
str.end();++ite r, ++i)
{
size_t len = (*iter).length( ) + 1;
strarr[i] = new char[len];
char *temp = new char[len];
strcpy(temp, (*iter).c_str() );
strcpy(strarr[i], temp);
}
return 0;
}
Nov 17 '05 #1
2 2051
jmd
I created a C++ Win32 project in Visual Studio 2005 containing your code.
Compile & link without error.
Run also without error !
. starr was set correctly with the addresses of the first char of each
C-style string.
. each memory at the corresponding address contains the correct entered
characters.

Good luck.
jean-marie
"Amrit Kohli" <am***@wayne.ed u> wrote in message
news:ei******** ******@TK2MSFTN GP14.phx.gbl...
Hello.

I have the following code, to do a simple operation by copying the
elements
of a vector of strings into an array of char pointers. However, when I
run
this code, the first element in the char array strarr[0] holds garbage
characters. For some reason, every time the strcpy function is called to
copy the string in temp to the array, it fills the 0th element in the
strarr
array with garbage characters. Can someone try to compile this code and
debug it and see if they get the same results that I'm getting? Any
insight
into why this might be happening? I'm really stumpped. The code works
for
every other element in strarr except for the 0th element. I've even tried
directly setting the strarr[0]th element to the pointer of temp with this
statement:

strarr[i] = temp; // where i = 0

and the pointer value gets set, but the characters are still garbage.
When
I look at the value of strarr[0] in the debugger, no matter how I assign
the
temp string to the array index, it always comes out as garbage, even when
the pointer is equal to the value of temp. The temp variable holds the
correct string, but for some reason, it won't properly copy into the 0th
element of the array.

Any help on this would be greatly appreciated.

Thanks -

#include <iostream>
#include <string>
#include <vector>
#include <bitset>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
vector<string> str;
string s;
while(cin >> s)
str.push_back(s );
const size_t array_size = 100;
char *strarr[array_size];
int i = 0;
for(vector<stri ng>::iterator iter = str.begin();ite r !=
str.end();++ite r, ++i)
{
size_t len = (*iter).length( ) + 1;
strarr[i] = new char[len];
char *temp = new char[len];
strcpy(temp, (*iter).c_str() );
strcpy(strarr[i], temp);
}
return 0;
}

Nov 17 '05 #2
Amrit Kohli wrote:
Hello.

I have the following code, to do a simple operation by copying the elements
of a vector of strings into an array of char pointers. However, when I run
this code, the first element in the char array strarr[0] holds garbage
characters. For some reason, every time the strcpy function is called to
copy the string in temp to the array, it fills the 0th element in the strarr
array with garbage characters. Can someone try to compile this code and
debug it and see if they get the same results that I'm getting? Any insight
into why this might be happening? I'm really stumpped. The code works for
every other element in strarr except for the 0th element. I've even tried
directly setting the strarr[0]th element to the pointer of temp with this
statement:

strarr[i] = temp; // where i = 0

and the pointer value gets set, but the characters are still garbage. When
I look at the value of strarr[0] in the debugger, no matter how I assign the
temp string to the array index, it always comes out as garbage, even when
the pointer is equal to the value of temp. The temp variable holds the
correct string, but for some reason, it won't properly copy into the 0th
element of the array.
This suggests to me that you are using the debugger incorrectly. If two
pointers have the same value, then they point to the same characters! If
you're seeing something strange in the debugger, the best option is to
put some output statements in the code to see what's going on.

The code looks ok as far as it goes, apart from memory leaks.
for(vector<stri ng>::iterator iter = str.begin();ite r !=
str.end();++ite r, ++i)
{
size_t len = (*iter).length( ) + 1;
strarr[i] = new char[len];
char *temp = new char[len];
strcpy(temp, (*iter).c_str() );
strcpy(strarr[i], temp);


You've got a memory leak here - the dynamic array you assigned to temp
is no longer accessible, and therefore leaks. You should instead have
something like:
size_t len = iter->length() + 1;
strarr[i] = new char[len];
strcpy(strarr[i], iter->c_str());

You also need to clean up strarr at the end.

Tom
Nov 17 '05 #3

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

Similar topics

10
6569
by: Noah Spitzer-Williams | last post by:
Hello guys, I'm itinerating through my array using pointers in this fashion: image is unsigned char image do { cout << "image byte is: " << *image << endl;
3
4152
by: Ian Taite | last post by:
Hello, I'm exploring why one of my C# .NET apps has "high" memory usage, and whether I can reduce the memory usage. I have an app that wakes up and processes text files into a database periodically. What happens, is that the app reads the contents of a text file line by line into an ArrayList. Each element of the ArrayList is a string representing a record from the file. The ArrayList is then processed, and the arraylist goes out of...
3
2291
by: Travis L Spencer | last post by:
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
12
9588
by: leonard.guillaume | last post by:
Hi guys, I use dynamic char arrays and I'm trying to get rid of the garbage in it. Let me show you the code and then I'll explain more in details. ---------------------------------------------------------------------------------------------------- CFile oFile("User.tcx", CFile::modeRead); CRijndael oDecrypt; long size; char* buffer,* buf;
142
6873
by: jacob navia | last post by:
Abstract -------- Garbage collection is a method of managing memory by using a "collector" library. Periodically, or triggered by an allocation request, the collector looks for unused memory chunks and recycles them. This memory allocation strategy has been adapted to C (and C++) by the library written by Hans J Boehm and Alan J Demers. Why a Garbage Collector? -----------------------
5
3696
by: junky_fellow | last post by:
Hi, I discussed about this earlier as well but I never got any satisfactory answer. So, I am initiating this again. Page 84, WG14/N869 "If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the
28
2110
by: onkar | last post by:
This idea might be vey crazy. But I hope to get answers to this .. from comp.lang.c If a compiler is designed such that it automatically adds a free() matching every malloc() then is it not a garbage collection (in the first place , garbage will not be generated !! ) . Is it possible to have a compiler with such feature. Or if Its not a good idea (or may be this is an idiotic idea) please tell me why is it so ??
21
2758
by: arnuld | last post by:
int main() { const char* arr = {"bjarne", "stroustrup", "c++"}; char* parr = &arr; } this gives an error: $ g++ test.cpp test.cpp: In function 'int main()': test.cpp:4: error: cannot convert 'const char* (*)' to 'char*' in
158
7915
by: pushpakulkar | last post by:
Hi all, Is garbage collection possible in C++. It doesn't come as part of language support. Is there any specific reason for the same due to the way the language is designed. Or it is discouraged due to some specific reason. If someone can give inputs on the same, it will be of great help. Regards, Pushpa
0
10577
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10332
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10320
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9150
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7620
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4299
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
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.