473,785 Members | 2,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Runtime error: std::bad_alloc at memory location

Hi,

I have the following code snippets and I get a std::bad_alloc error
where I think there should be none. I've attached the relevant bits of
the base class, derived class and the .cpp file containing the main()
method.

I'd really appreciate any help in getting this error sorted out.

Thanks,
Anuj
Base class:

onst int DESCRIPTION_LEN GTH = 128;

class InventoryItem {

private:
char* itemDescription ;
int itemQuantity;
double itemCost;

void assignDescripti on(const char* desc) {
int stringLength = strlen(desc);
itemDescription = new char[stringLength + 1];
strncpy(itemDes cription, desc, DESCRIPTION_LEN GTH);
}

public:
// Constructor
InventoryItem(c onst char* desc, int qty, double cost) {
assignDescripti on(desc);
itemQuantity = qty;
itemCost = cost;
}

// Destructor
~InventoryItem( void) {
delete [] itemDescription ;
}
}

Derived class:

const int DEFAULT_SIZE = 20;

class InventoryList {

private:
InventoryItem **inventory;
int count;

public:
// Constructor
InventoryList(v oid) {
inventory = new InventoryItem*[DEFAULT_SIZE];
count = 0;
}
// Destructor
~InventoryList( void) {
for (int i = 0; i < count; i++)
delete inventory[i];
delete [] inventory;
}

// Method to add InventoryItem object to InventoryList object
void addItem(Invento ryItem* item) {
inventory[count++] = item;
}
}

Main .cpp:

#include "InventoryItem. h"
#include "InventoryList. h"
#include <iostream>

using namespace std;

int main(void)
{
InventoryList* inventory = new InventoryList[10];

inventory->addItem(new InventoryItem(" wrench", 3, 21.99));
inventory->addItem(new InventoryItem(" hammer", 9, 1.99));
inventory->addItem(new InventoryItem(" pliers", 2, 2.99));
inventory->addItem(new InventoryItem(" saw", 6, 3.99));

inventory->printList();

return 0;
}

Nov 11 '06 #1
3 18109
schizoid_man wrote:
...
I have the following code snippets and I get a std::bad_alloc error
where I think there should be none. I've attached the relevant bits of
the base class, derived class and the .cpp file containing the main()
method.
One can find many obvious and potential problems with your code if one
assumes that this is a _complete_ code. I will assume that this is just
a fragment, so I'll consider only the problems with the code that is
explicitly present here.

Also, I don't see any "base" and "derived" classes in your code. You
have two unrelated (from the language point of view) classes. Anyway...
>
Base class:
It is not really a "base" for anything in the quoted code...
onst int DESCRIPTION_LEN GTH = 128;
const int?
>
class InventoryItem {

private:
char* itemDescription ;
int itemQuantity;
double itemCost;

void assignDescripti on(const char* desc) {
int stringLength = strlen(desc);
itemDescription = new char[stringLength + 1];
strncpy(itemDes cription, desc, DESCRIPTION_LEN GTH);
Here you allocate 'stringLength + 1' bytes of memory, but then you copy
up to 'DESCRIPTION_LE NGTH' bytes into the allocated block. Remember,
this 'strncpy' will _always_ overwrite 'DESCRIPTION_LE NGTH' bytes in the
target memory block, even it the source string is shorter than that. In
case when 'desc' is shorter, the 'strncpy' won't stop, but rather it
will fill the remaining bytes of the destination block with zeros.

In other words, here you have a clear case of memory overrun - a very
real reason of undefined behavior, which can easily lead to the
'bad_alloc' exception. 'strncpy' is not what you need in this case. In
this case you can safely use 'strcpy' instead. (Frankly, I don't
understand why you even need that 'DESCRIPTION_LE NGTH' in your code).

Better yet, get rid of manual memory management and learn to use
'std::string' instead.
}

public:
// Constructor
InventoryItem(c onst char* desc, int qty, double cost) {
assignDescripti on(desc);
itemQuantity = qty;
itemCost = cost;
}

// Destructor
~InventoryItem( void) {
delete [] itemDescription ;
}
}
Derived class:
It is not really "derived".. .
const int DEFAULT_SIZE = 20;

class InventoryList {

private:
InventoryItem **inventory;
int count;

public:
// Constructor
InventoryList(v oid) {
'void' is not required here (as well as in other functions)... But
that's a matter of personal preference.
inventory = new InventoryItem*[DEFAULT_SIZE];
count = 0;
}
// Destructor
~InventoryList( void) {
for (int i = 0; i < count; i++)
delete inventory[i];
delete [] inventory;
}

// Method to add InventoryItem object to InventoryList object
void addItem(Invento ryItem* item) {
inventory[count++] = item;
Since you don't grow your memory, it makes sense to check for the array
size here. Make sure you don't go over 'DEFAULT_SIZE' elements.

Or, better yet, learn to use 'std::vector<>' instead of allocating
arrays with 'new[]'.
}
}
Main .cpp:

#include "InventoryItem. h"
#include "InventoryList. h"
#include <iostream>

using namespace std;

int main(void)
{
InventoryList* inventory = new InventoryList[10];
Hm... You allocate an array of 10 'InventoryList' s but use only the
first element later. What was the point of allocating 10 of them?
Although this is not a reason for the exception...
inventory->addItem(new InventoryItem(" wrench", 3, 21.99));
inventory->addItem(new InventoryItem(" hammer", 9, 1.99));
inventory->addItem(new InventoryItem(" pliers", 2, 2.99));
inventory->addItem(new InventoryItem(" saw", 6, 3.99));

inventory->printList();

return 0;
}
Aside from missing 'delete[]' (and no implementation for 'printList')
this 'main' looks fine. The most likely reason for the exception is that
'strncpy' in 'assignDescript ion'.

--
Best regards,
Andrey Tarasevich

Nov 11 '06 #2
schizoid_man wrote:
Hi,

I have the following code snippets and I get a std::bad_alloc error
where I think there should be none. I've attached the relevant bits of
the base class, derived class and the .cpp file containing the main()
method.

I'd really appreciate any help in getting this error sorted out.

Thanks,
Anuj
Base class:

onst int DESCRIPTION_LEN GTH = 128;
I assume u mean "c"onst
>
class InventoryItem {

private:
char* itemDescription ;
int itemQuantity;
double itemCost;

void assignDescripti on(const char* desc) {
int stringLength = strlen(desc);
itemDescription = new char[stringLength + 1];
strncpy(itemDes cription, desc, DESCRIPTION_LEN GTH);
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
This is your error. You're copying more bytes than allocated.
}

public:
// Constructor
InventoryItem(c onst char* desc, int qty, double cost) {
assignDescripti on(desc);
itemQuantity = qty;
itemCost = cost;
}

// Destructor
~InventoryItem( void) {
delete [] itemDescription ;
}
}
// needs a ";"
>
Derived class:

const int DEFAULT_SIZE = 20;

class InventoryList {

private:
InventoryItem **inventory;
int count;

public:
// Constructor
InventoryList(v oid) {
inventory = new InventoryItem*[DEFAULT_SIZE];
count = 0;
}
// Destructor
~InventoryList( void) {
for (int i = 0; i < count; i++)
delete inventory[i];
delete [] inventory;
}

// Method to add InventoryItem object to InventoryList object
void addItem(Invento ryItem* item) {
inventory[count++] = item;
}
}
needs another ";"
>
Main .cpp:

#include "InventoryItem. h"
#include "InventoryList. h"
#include <iostream>

using namespace std;

int main(void)
{
InventoryList* inventory = new InventoryList[10];

inventory->addItem(new InventoryItem(" wrench", 3, 21.99));
inventory->addItem(new InventoryItem(" hammer", 9, 1.99));
inventory->addItem(new InventoryItem(" pliers", 2, 2.99));
inventory->addItem(new InventoryItem(" saw", 6, 3.99));

inventory->printList();
// function does not exist
>
return 0;
}
Give up on cstrings already... Use std::string and std::vector.

e.g.
#include <string>
#include <vector>

class InventoryItem {

private:
std::string itemDescription ;
int itemQuantity;
double itemCost;

void assignDescripti on(const char * desc)
{
itemDescription = desc;
}

public:
// Constructor
InventoryItem(c onst char* desc, int qty, double cost)
: itemDescription ( desc ),
itemQuantity( qty ),
itemCost( cost )
{
}
};

//Derived class:

const int DEFAULT_SIZE = 20;

class InventoryList {

private:
std::vector< InventoryItem inventory;
int count;

public:
// Constructor
InventoryList(v oid)
{
}

// Destructor
~InventoryList( void) {
}

// Method to add InventoryItem object to InventoryList object
void addItem(const InventoryItem& item)
{
inventory.push_ back( item );
}
};

//Main .cpp:

//#include "InventoryItem. h"
//#include "InventoryList. h"
#include <iostream>

using namespace std;

int main(void)
{
InventoryList* inventory = new InventoryList[10];

inventory->addItem(Invent oryItem("wrench ", 3, 21.99));
inventory->addItem(Invent oryItem("hammer ", 9, 1.99));
inventory->addItem(Invent oryItem("pliers ", 2, 2.99));
inventory->addItem(Invent oryItem("saw", 6, 3.99));

// inventory->printList();

return 0;
}


Nov 12 '06 #3
Gianni Mariani wrote:
> void assignDescripti on(const char* desc) {
int stringLength = strlen(desc);
itemDescription = new char[stringLength + 1];
strncpy(itemDes cription, desc, DESCRIPTION_LEN GTH);
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
Thank you both Gianni and Andrey. Replacing strncpy with strcpy did the
trick. As you'd noted, the code was not complete, but I thought I'd just
attach the relevant bits.

Thanks for the tip on <stringand <vector>. I'm going to take a look at
using both.
Nov 12 '06 #4

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

Similar topics

1
2349
by: abhilash agarwal | last post by:
hi all!! pl help me i m getting a run time error "memory address .... refer to this location....... memory could not be written at this location....." ..... means some memory address when i m trying to run a programme in which i m setting line style to any color except "0" which is for BLACK
5
2181
by: Asfand Yar Qazi | last post by:
Hi, Just wondering, if I do a: std::set_new_handler(std::terminate) I won't have to worry about a std::bad_alloc being thrown when I do a 'new ...' or a 'new(nothrow) ...', right? Its just that I'm writing a Ruby extension, and I tried wrapping C++
5
1725
by: He Shiming | last post by:
Hi, I have a question regarding memory consumption of class/object member functions. Say that I have: class A { char szAbc; char* getString(); }
2
1784
by: Mark | last post by:
Hello. I have developed a custom webbrowser for my son with features like group browsing etc. So far so good. The program works fine. But then, when I look into the memory usage the programme is using tons of megabytes of memory. With 10 pages open, the programme is consuming about 60 MB of memory. Without any webpage loaded, my custom browser uses about 45 MB of memory. Opera on the other hand uses 15 megabytes on start up. With the same...
14
29139
by: Mohsen | last post by:
Hello everyone, In my program, I have to define many pointers and when I want to compile my program (in UNIX), it gives me the following error: terminate called after throwing an instance of 'std::bad_alloc' what(): St9bad_alloc Abort I rechecked those pointers; I found I cannot decrease the size of them.
4
2995
by: sndive | last post by:
Do linux kernels 2.4 and 2.6 have some stash of memory set aside to handle paging in std::bad_alloc or ... exception handling code when new or new throws that exception? How is that handled? Does gcc generate some report to the elf loader that the largest exception handling section is x kb long or what?
1
2895
by: Curten | last post by:
Hi, When I run a program I have made, i get this error message sometimes: "Application error:The instruction at '...' referenced memory at '...'. Memory could not be "read"..." Are there any common mistakes that cause this problem? Before i get the message above i get this in the command window: "pow: OVERFLOW error". I suppose these error messages are connected, but how? What causes pow: OVERFLOW error?
3
2123
jhardman
by: jhardman | last post by:
I was in the middle of troubleshooting a different problem when my web service stopped working with a very cryptic error message: "specified cast is not valid" The only location info is that the error came from the web method I called (which is pretty obvious) and this method is gigantic. Arghh. And the web service is running at a remote location - it has no developer tools installed. When I try to pull it up on my box it works - no error,...
2
2296
by: itxharsh | last post by:
The error during run time is:"Your code has stopped its execution with a non-zero (failure) exit value.This is generally due to run time Exceptions like Memory Access Violation and Floating Point Exception. Please check your code for run time Exceptions and try again.". What could be the error? Please help. #include<conio.h> #include<stdio.h> struct amicable { int **amicablePairs; int size; }; struct amicable* getAmicablePairs(int...
0
10147
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
10087
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
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7496
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
5380
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
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
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
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.