473,666 Members | 2,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Messed Up Char Array


hi,

wrote the following program to learn a bit about auto pointers.

weird thing is, the char array 'name' with size 'max_size' displays a
bunch of messed up symbols after the "John Smith" if max_size is larger
than 28. why is that? I found this out by playing with max_size after
I couldn't figure out what I did wrong.

thx a bunch
#include <iostream>
using namespace std;

class Contact_Info {
static const int max_size = 28;
char name[max_size];
int phone_number;
public:
Contact_Info() {
char ee[] = "Empty entry.";
int x = 0;

while(ee[x]) {
name[x] = ee[x++];
}

phone_number = NULL;
}
Contact_Info(ch ar* ptr) {
int x = 0;

while(name[x]) {
name[x++] = NULL;
}

x = 0;

while(*ptr) {
name[x++] = *ptr++;
}

phone_number = NULL;
}
Contact_Info(ch ar* ptr, int a) {
int x = 0;

while(name[x]) {
name[x++] = NULL;
}

x = 0;

while(*ptr) {
name[x++] = *ptr++;
}

phone_number = a;
}
void display_all() {
int x = 0;
cout << "Name: ";

while(name[x]) {
cout << name[x++];
}

cout << "\n\nPhone number: " << phone_number <<
"\n\n\n\n";
}
};

int main() {
Contact_Info Sample("John Smith", 1234567);

auto_ptr<Contac t_Info> ap(&Sample);
auto_ptr<Contac t_Info> ap2(new Contact_Info()) ;

ap->display_all( );

ap2->display_all( );

ap2 = ap;

//ap->display_all( ); //This line causes program crash (ap now
points to nothing).

ap2->display_all( );

cin.get();
}

Aug 29 '05 #1
6 2312
<A_*********@ho tmail.com> wrote in message
news:11******** ************@z1 4g2000cwz.googl egroups.com...
[...]
class Contact_Info {
static const int max_size = 28;
char name[max_size];
int phone_number; [...] Contact_Info(ch ar* ptr, int a) {
int x = 0;

while(name[x]) {
name[x++] = NULL;
}

[...]

The contents of the array (name) are uninitialized. You could easily walk
off the end of the array if you look for a '\0' to stop the loop. That
could explain the strange behavior you're seeing.

Change the while loop to something like

for ( x = 0; x < max_size; ++x ) {
name[x] = '\0';
}

--
David Hilsee
Aug 29 '05 #2

appreciate it, David. thx.
David Hilsee wrote:
<A_*********@ho tmail.com> wrote in message
news:11******** ************@z1 4g2000cwz.googl egroups.com...
[...]
class Contact_Info {
static const int max_size = 28;
char name[max_size];
int phone_number;

[...]
Contact_Info(ch ar* ptr, int a) {
int x = 0;

while(name[x]) {
name[x++] = NULL;
}

[...]

The contents of the array (name) are uninitialized. You could easily walk
off the end of the array if you look for a '\0' to stop the loop. That
could explain the strange behavior you're seeing.

Change the while loop to something like

for ( x = 0; x < max_size; ++x ) {
name[x] = '\0';
}

--
David Hilsee


Aug 29 '05 #3
A_*********@hot mail.com wrote:

wrote the following program to learn a bit about auto pointers.
weird thing is, the char array 'name' with size 'max_size'
displays a bunch of messed up symbols after the "John Smith"
if max_size is larger than 28. why is that? I found this out
by playing with max_size after I couldn't figure out what I
did wrong.

class Contact_Info {
static const int max_size = 28;
char name[max_size];
At this point name[] looks like: [??????????????? ????????????]
ie. it is initialized to garbage. (I use sq brackets instead
of quote marks to emphasize that it is an array, not a string).
int phone_number;
public:
Contact_Info() {
char ee[] = "Empty entry.";
int x = 0;

while(ee[x]) {
name[x] = ee[x++];
}
Now name looks like: [Empty entry.????????? ???????]
Note that there is no end-of-string marker in this.

phone_number = NULL;
NULL should only be used for pointers. Use a plain 0 for
numbers.
}
Contact_Info(ch ar* ptr) {
int x = 0;

while(name[x]) {
name[x++] = NULL;
}
Are you sure you know what " while(name[x]) " does ? It will keep
going as long as the x'th char in the name array is not an
end-of-string marker. If you run past the end of the array, this
loop doesn't care, it will keep on reading whatever happened to
be in memory after the array.

Since name[] currently contains garbage (see above), it is just
a matter of chance as to whether this code writes all over your
memory space, or it encounters an end-of-string marker and stops.

My advice would be to get rid of that loop entirely, since you
are just about to assign values to name[] in the next section!

x = 0;

while(*ptr) {
name[x++] = *ptr++;
}
Now name will be [John Smith?????????? ????????]. Note that there
is still no end-of-string marker in Name.

phone_number = NULL;
}
void display_all() {
int x = 0;
cout << "Name: ";

while(name[x]) {
cout << name[x++];
}
This will simply keep displaying characters from name[] until
it runs into an end-of-string marker. Above, we worked out what
name[] contains. So now it should be no surprise that it displays
the string, and then some quantity (possibly endless) of garbage.

Now we move onto the auto pointers :)
int main() {
Contact_Info Sample("John Smith", 1234567);

auto_ptr<Contac t_Info> ap(&Sample);
A bad idea. Since 'Sample' is an automatic object, it will
automatically be deleted when it goes out of scope. Your code
will try to delete it twice (causing undefined behaviour).
auto_ptr<Contac t_Info> ap2(new Contact_Info()) ;
Better :)
Note that those extra brackets are a waste of space:
auto_ptr<Contac t_Info> ap2(new Contact_Info);
ap->display_all( );
ap2->display_all( );
ap2 = ap;
This statement will free ap2 (I think!), and transfer ownership
from ap to ap2. Now ap points to nothing, and ap2 points to
Sample.
//ap->display_all( ); //This line causes program crash
(ap now points to nothing).
Correct.
ap2->display_all( );

cin.get();
}


As mentioned before, now you may also get a crash, as Sample gets
deleted twice.

Aug 29 '05 #4
On Sun, 28 Aug 2005 17:26:35 -0700, A_StClaire_ wrote:
name[x] = ee[x++];


In addition to the other comments, I would not do the above. I don't think
you have any guarantees about what "x" will be when name[x] is evaluated.

- Jay
Aug 29 '05 #5
A_*********@hot mail.com wrote:
hi,

wrote the following program to learn a bit about auto pointers.
[redacted]
int main() {
Contact_Info Sample("John Smith", 1234567);

auto_ptr<Contac t_Info> ap(&Sample);
NO NO NO NO NO NO NO NO NO!!!
DO NOT DO THIS!!! EVER!!!

auto_ptr<> will delete its pointer when it goes out of scope or is
reassigned. Sample was not dynamically allocated, so somewhere down the
line, you will attempt to delete a non-dynamically allocated variable.

auto_ptr<Contac t_Info> ap2(new Contact_Info()) ;

ap->display_all( );

ap2->display_all( );

ap2 = ap;

//ap->display_all( ); //This line causes program crash (ap now
points to nothing).

ap2->display_all( );

cin.get();
}

Aug 29 '05 #6

thx for all the helpful admonitions, guys.
red floyd wrote:
A_*********@hot mail.com wrote:
hi,

wrote the following program to learn a bit about auto pointers.
[redacted]


int main() {
Contact_Info Sample("John Smith", 1234567);

auto_ptr<Contac t_Info> ap(&Sample);


NO NO NO NO NO NO NO NO NO!!!
DO NOT DO THIS!!! EVER!!!

auto_ptr<> will delete its pointer when it goes out of scope or is
reassigned. Sample was not dynamically allocated, so somewhere down the
line, you will attempt to delete a non-dynamically allocated variable.

auto_ptr<Contac t_Info> ap2(new Contact_Info()) ;

ap->display_all( );

ap2->display_all( );

ap2 = ap;

//ap->display_all( ); //This line causes program crash (ap now
points to nothing).

ap2->display_all( );

cin.get();
}


Aug 31 '05 #7

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

Similar topics

35
20940
by: Ying Yang | last post by:
Hi, whats the difference between: char* a = new char; char* b = new char; char c ;
21
18857
by: Bret | last post by:
I'm curious why char** argv is acceptable in the main() declaration. In the comp.lang.c FAQ (question 6.18) it says that pointers to pointers and pointers to an array are not interchangable. However the declaration: int main(int argc, char** argv) is common.
19
14509
by: gaga | last post by:
I can't seem to get this to work: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *names; char **np;
5
3962
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
12
5502
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the following program: #include<stdio.h> #define SIZE 1 int main()
13
2113
by: chellappa | last post by:
hi , please explain me , char pointer , char Array, char ,string... i have some many confussion about this... please clarify to me.. i need some example about this program by chellappa.ns
15
34583
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
5
7783
by: Stephen Cawood | last post by:
I'm trying to use a C++ .lib from C# (I tried the Interop group will no results). I have a working wrapper DLL (I can get back simple things like int), but I'm having issues dealing with an array of bytes. For example, the .lib contains this function: int create(int id, int scale, unsigned char *image); In the wrapper DLL I have this function:
3
3487
by: ZMan | last post by:
The following code won't compile with gcc version 3.4.2 (mingw-special). How come? Error: cannot convert `char (*)' to `char**' /**********************************************************/ #include <cstdio> #define MAX_WORD_LEN 80 #define MAX_SIZE 1000
0
8440
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8780
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
8549
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,...
1
6189
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
4192
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1763
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.