473,769 Members | 2,246 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can you fix this program? : C++ Dynamic Array Problems

I have written the following program using VS2005. The program is a Dynamic
Array similar to System.Collecti ons.ArrayList in .NET. The program works
okay until I reach 65536, I can't seem to figure out why, as it seems my
logic is working okay. I am a .NET programmer so I am not used to dealing
with un-managed C++ code. Please criticize my code if you think it is poorly
written.

This is the loop from main() that will blow up the program if you change
65536 to a larger value.
for(int i = 0; i < 65536; i++)
{
folder.entryID = "Testing";
fc->Add(folder);
}

Thanks
Russell Mangel
Las Vegas, NV

// Begin Code
#include "stdafx.h"
#include <iostream>

using namespace std;

struct Folder
{
char *entryID;
};
class FoldersCollecti on
{
public:
FoldersCollecti on::FoldersColl ection()
{
Count = 0;
Capacity = 0;
}
FoldersCollecti on::~FoldersCol lection()
{
delete []m_Folders;
}
int Count;
int Capacity;
void FoldersCollecti on::Add(Folder folder)
{
if(Capacity == 0)
{
m_Folders = new Folder[INITIAL_CAPACIT Y];
m_Folders[0].entryID = folder.entryID;
Count ++;
Capacity = INITIAL_CAPACIT Y;
}
else
{
if(Count < Capacity)
{
m_Folders[Count].entryID = folder.entryID;
Count ++;
}
else
{
printf("Resizin g Array. Capacity: %d.\n", Capacity);
Resize();

m_Folders[Count].entryID = folder.entryID;
Count ++;
}
}
}
Folder* FoldersCollecti on::GetList()
{
return m_Folders;
}
private:
Folder *m_Folders;
Folder *m_Temp;
static const int INITIAL_CAPACIT Y = 4;
void FoldersCollecti on::Resize()
{
// Double Capacity
int newCapacity = Capacity*=2;
// Create new Array
m_Temp = new Folder[newCapacity];
// Copy elements
for(int i = 0; i < Capacity; i++)
{
m_Temp[i].entryID = m_Folders[i].entryID;
}

delete []m_Folders;
m_Folders = m_Temp;
Capacity = newCapacity;
}
};
void main(void)
{
FoldersCollecti on *fc = new FoldersCollecti on;
Folder folder;

// Works okay up to 65536, change to larger value to crash program...
// What I am doing wrong...
for(int i = 0; i < 65536; i++)
{
folder.entryID = "Testing";
fc->Add(folder);
}
printf("Finishe d... Count: %d Capacity: %d \n", fc->Count, fc->Capacity);
delete fc;
}
Mar 7 '06 #1
10 1707
"Russell Mangel" <ru*****@tymer. net> wrote in message
news:%2******** ********@TK2MSF TNGP15.phx.gbl. ..
<snip>

void FoldersCollecti on::Resize()
{
// Double Capacity
int newCapacity = Capacity*=2;
You probably meant:
int newCapacity = Capacity*2;
// Create new Array
m_Temp = new Folder[newCapacity];
// Copy elements
for(int i = 0; i < Capacity; i++)
{
m_Temp[i].entryID = m_Folders[i].entryID;
}

As it is now, the index goes beyond the allocated capacity of m_Folders
after midway through the loop.
Mar 7 '06 #2
> int newCapacity = Capacity*=2;
// Create new Array
m_Temp = new Folder[newCapacity];
// Copy elements
for(int i = 0; i < Capacity; i++)
{
m_Temp[i].entryID = m_Folders[i].entryID;
}


Hi,

you double the capacity variable and then index the original array beyond
its boundaries.
the fact that it worked until 65536 is pure luck.

My personal opinion is that you should never combine multiple statements and
assignments on 1 line. it is much too easy to make mistakes.

Had you written it like this, you would have seen the problem almost
immediatly probably.
Capacity*=2
int newCapacity = Capacity;

--

Kind regards,
Bruno.
br************* *********@hotma il.com
Remove only "_nos_pam"
Mar 7 '06 #3
Russell Mangel wrote:
I have written the following program using VS2005. The program is a
Dynamic Array similar to System.Collecti ons.ArrayList in .NET. The
program works okay until I reach 65536, I can't seem to figure out
why, as it seems my logic is working okay. I am a .NET programmer so
I am not used to dealing with un-managed C++ code. Please criticize
my code if you think it is poorly written.
The main criticism would be why write it at all? This code is spelled
std::vector<T> in C++. There's simply no need to write code like this
except for the learning exercise of it. A few other criticisms inline
below.

This is the loop from main() that will blow up the program if you
change 65536 to a larger value.
for(int i = 0; i < 65536; i++)
{
folder.entryID = "Testing";
fc->Add(folder);
}

Thanks
Russell Mangel
Las Vegas, NV

// Begin Code
#include "stdafx.h"
#include <iostream>

using namespace std;

struct Folder
{
char *entryID;
};
Should the above have a destructor? In your example, you're only assigning
character literals to entryID, so the answer is NO, but in the real world,
that might be a different story. If entryID needs to be delete[]'d, then
you should define a destructor, assignment operator and copy constructor for
this class.
class FoldersCollecti on
{
public:
FoldersCollecti on::FoldersColl ection()
{
Count = 0;
Capacity = 0;
}
FoldersCollecti on::~FoldersCol lection()
{
delete []m_Folders;
}
int Count;
int Capacity;
You might want to wrap these fields in accessors. As is, a client can
simply change your Count or Capacity, breaking your class from the outside.
void FoldersCollecti on::Add(Folder folder)
{
if(Capacity == 0)
{
m_Folders = new Folder[INITIAL_CAPACIT Y];
m_Folders[0].entryID = folder.entryID;
Count ++;
Capacity = INITIAL_CAPACIT Y;
}
else
{
if(Count < Capacity)
{
m_Folders[Count].entryID = folder.entryID;
Count ++;
}
else
{
printf("Resizin g Array. Capacity: %d.\n", Capacity);
Resize();

m_Folders[Count].entryID = folder.entryID;
Count ++;
}
}
}
Rewrite the above:

void FoldersCollecti on::Add(Folder folder)
{
EnsureCapacity( Count+1);
m_Folders[Count++] = folder;
}
Folder* FoldersCollecti on::GetList()
{
return m_Folders;
}
If you're going to simply expose the inner array, there's little point in
even making a class since a client can simply run roughshod all over your
array once you've returned a pointer. I'd reconsider this design.
private:
Folder *m_Folders;
Folder *m_Temp;
Eliminiate the above member varialbe- m_Temp
static const int INITIAL_CAPACIT Y = 4;
void FoldersCollecti on::Resize()
{
// Double Capacity
int newCapacity = Capacity*=2;
// Create new Array
m_Temp = new Folder[newCapacity];
// Copy elements
for(int i = 0; i < Capacity; i++)
{
m_Temp[i].entryID = m_Folders[i].entryID;
}

delete []m_Folders;
m_Folders = m_Temp;
Capacity = newCapacity;
}
Rewrite this:

void FoldersCollecti on::EnusreCapac ity(int requiredCapacit y)
{
if (requiredCapaci ty <= Capacity)
return;

int newCapacity = Capacity*2;
if (newCapacity < INITIAL_CAPACIT Y)
newCapacity = INITIAL_CAPACIT Y;
if (newCapacity < requiredCapacit y)
newCapacity = requiredCapacit y;

Folder* temp = new Folder[newCapacity];

if (Count > 0)
{
for (int i = 0; i < Count; ++i)
temp[i] = m_Folders[i];
delete[] m_Folders;
}

m_Folders = temp;
}
};
void main(void)
{
FoldersCollecti on *fc = new FoldersCollecti on;
Folder folder;

// Works okay up to 65536, change to larger value to crash program...
// What I am doing wrong...
for(int i = 0; i < 65536; i++)
{
folder.entryID = "Testing";
fc->Add(folder);
}
printf("Finishe d... Count: %d Capacity: %d \n", fc->Count,
fc->Capacity); delete fc;
}

Mar 7 '06 #4
> You probably meant:
int newCapacity = Capacity*2;
As it is now, the index goes beyond the allocated capacity of m_Folders
after midway through the loop.


This fixes the worst of my problems, thanks...
Russ.
Mar 7 '06 #5
> Carl Daniel wrote: The main criticism would be why write it at all? This
code is spelled std::vector<T> in C++. There's simply no need to write
code like this except for the learning exercise of it. A few other
criticisms inline below.


The reason I didn't use std:vector is because I don't know how to marshal
the vector back to a Managed .NET client. I am dealing with an API which has
no managed equivilant "Extended MAPI 1.0". and I am calling this code from
Un-Managed clients and Managed clients. Of course I could loop through the
vector in Un-Managed code to build an Folder[] and return it to the clients,
but then this would be an additional loop. Is my thinking good here? Maybe
you have a better idea now that you know a little more what I am trying to
accomplish..

When doing C++/CLI Interop there are so many ways of doing things, it's head
spinning. My intention is to minimize marshalling data across the
Managed/Un-Managed zone. My idea is too pass a single string to the
unmanaged code, and then let the un-managed code build a collection and
return a pointer to the data. For a total of two Interops.

Thanks for taking the time to reply.
Russell Mangel
Las Vegas, NV
Mar 7 '06 #6
>> struct Folder {
char *entryID;};


Should the above have a destructor? In your example, you're only
assigning character literals to entryID, so the answer is NO, but in the
real world, that might be a different story. If entryID needs to be
delete[]'d, then you should define a destructor, assignment operator and
copy constructor for this class.


This is a great suggestion, and also exposes my weakness when programming in
Native C++ "Memory Management".

I don't know how to delete the memory on the heap for *folder. How would I
delete the memory once it gets inside the FoldersCollecti on when program is
finished?

Thanks
Russell Mangel

void main (void){
FoldersCollecti on *fc = new FoldersCollecti on;
Folder *folder = new Folder;

for(int i = 0; i < 16384; i++) {
folder->entryID = "Testing";
fc->Add(folder); }
}

Mar 7 '06 #7

"Carl Daniel >
If you're going to simply expose the inner array, there's little point in
even making a class since a client can simply run roughshod all over your
array once you've returned a pointer. I'd reconsider this design.


Is there some way I could return this (read-only), so the clients can not
change the list?

Thanks,
Russell Mangel
Mar 7 '06 #8
>> If you're going to simply expose the inner array, there's little point in
even making a class since a client can simply run roughshod all over your
array once you've returned a pointer. I'd reconsider this design.


Is there some way I could return this (read-only), so the clients can not
change the list?


Not really. The best you can do is to return a const pointer, but even then
the caller is able to simply
cast away the const qualifier.

What you could do is to provide your own [] operator and not expose your
inner array.
that would give you the ability to implement bounds checking. your []
operator returns a copy of the actual
element, which the caller can abuse, but at least he won't mess up your
internal data.

That would result in more marshalling of course.

another thing you can do is to provide a function to which the caller has to
supply a pre allocated array that you can fill in.

As you said, there are multiple ways of doing things from which you can
choose, depending on needs and taste.

--

Kind regards,
Bruno.
br************* *********@hotma il.com
Remove only "_nos_pam"
Mar 7 '06 #9
> Bruno wrote:
What you could do is to provide your own [] operator and not expose your
inner array.
that would give you the ability to implement bounds checking. your []
operator returns a copy of the actual
element, which the caller can abuse, but at least he won't mess up your
internal data.

That would result in more marshalling of course.


This idea of yours may work, I'm not sure that this would cause any extra
marshalling. Maybe you can think about this a little more. Why would this
cause more marshalling?

What I am trying to do:
=============== =
Pass a single string to Unmanaged code (First Marshal).
Unmanaged code loops and gathers an array of strings (char *).
Unmanaged code returns a pointer to the innerArray[] (Second Marshal).

Both managed and unmanaged clients can now unwind/access the inner array
using the [] operator.

What am I missing? This shouldn't cause any more marshaling should it?

Russell Mangel
Las Vegas, NV

PS
The Folder struct will have more members than were initially listed, there
will be at least 8 members consisting of:
3 Byte[] arrays, 2 Int32's, 1 Int64, 2 Strings.


Mar 7 '06 #10

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

Similar topics

5
3408
by: meyousikmann | last post by:
I am having a little trouble with dynamic memory allocation. I am trying to read a text file and put the contents into a dynamic array. I know I can use vectors to make this easier, but it has to be done using dynamic arrays. I don't know the size of the text file ahead of time, though, so I created a class that includes a method to resize the array. Here is that class: class Data { public: Data(int initialsize);
6
4342
by: phkram | last post by:
Hello everybody... i find this place very helpful. anyone who can help me solve the following problems? Thank you very much for helping me.. 1. Build a header file that consists of a class Integer. The class should be capable of computing the sum, difference, product, quotient, and factorials of two numbers. Build an implementation file that uses the newly-built ADT(Abstract Data Type) Integer 2. Write a program that will determine the...
13
8949
by: kwikius | last post by:
Does anyone know what a C99 dynamic array is, and if it will be useable in C++? regards Andy Little
0
9579
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
9422
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10206
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
8863
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...
0
5293
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
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
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
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2811
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.