473,804 Members | 3,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

memory not allocated

kk
Hi all,
i didn't get output in the following code while compiling and executing
with g++ version 3.2.3 it doesn't allocate memory to pointer varaible
(x) in class B. and it gives correct output while executing in .Net and
visual slick editor. why it didn't allocate memory? if anybody knows
plz give reply.
thanks in advance

kk

------File Name: les9_5.C--------------
#include <iostream>
#include <string.h>
using namespace std;
class B{
char *x;
public:
B(char *y="xxx"):x(ne w char[strlen(y)+1]){
try{
// x=new char[strlen(y)+1];
if(*x)
strcpy(x,y);
else
{
cout<<"value at x\t"<<x<<endl;
cout<<y<<endl;//checkig formal
parameter
throw 1;
}
}catch(...){
cout<<"Construc tor B(char *y=\"xxx\") "<<endl;
cout<<"memory allocation failure"<<endl;
}
}
B(B *objb):x(new char[strlen(objb->x)+1])
{
cout<<"construc tor B(B *objb):x(new
char[strlen(objb->x)+1])"<<end*l;
if(*x)
strcpy(x,objb->x);
else
cout<<"memory allocation failure"<<endl;
}
B(const B& objb)
{
x=new char[strlen(objb.x)+ 1];
if(*x)
strcpy(x,objb.x );
else
cout<<"memory allocation failure"<<endl;
}
void showx()
{
cout<<"value of x from the object of class
B="<<x<<endl; }
~B(){
try{
if(*x)
delete []x;
else throw 2;
}catch(...){
cout<<"memory already deleted"<<endl;
}
}
};
class A{
char *y;
B *b;

public:
A(char *c="xxx",char *d="bbb"):y(ne w char[strlen(c)+1]),b(new
B(d)){
try{
// y=new char[strlen(c)+1];
// b=new B(d);
if(*y||*d)
strcpy(y,c);
else
throw 2;
}catch(...){
cout<<"memory allocation failure";
}
}
void showy()
{
cout<<"value of y from the object of class
B="<<y<<endl;
b->showx();
}
~A(){
try{
if(*y)
delete []y;
else throw 2;
/* if(*b)
delete []b;
else throw 2;
*/
}catch(...){
cout<<"memory already deleted in A's
destructor"<<en dl;
}
}

};
main()
{
A a("Hello","Gate s");
a.showy();
}
compiling: g++ -g -o les9_5 les9_5.C
executing: ./les9_5
output:
value at x
Gates
Constructor B(char *y="xxx")
memory allocation failure
value of y from the object of class B=Hello
value of x from the object of class B=

Jul 26 '05 #1
4 2090
* kk:
Hi all,
i didn't get output in the following code while compiling and executing
with g++ version 3.2.3 it doesn't allocate memory to pointer varaible
(x) in class B. and it gives correct output while executing in .Net and
visual slick editor. why it didn't allocate memory? if anybody knows
plz give reply.
thanks in advance
Uhuh. This must be the worst formatted code I've ever responded to here.
Please do something about that, and DON'T post with MIME-coding.

------File Name: les9_5.C--------------
To help your tools help you, use a filename that's recognized as C++ source
code.

#include <iostream>
#include <string.h>
using namespace std;
class B{
char *x;
public:
B(char *y=3D"xxx"):x(n ew char[strlen(y)+1]){
try{
// x=3Dnew char[strlen(y)+1];
'x' is already initialized. This new allocation means you're discarding the
pointer to the previously allocated memory, without deallocating it. You're
leaking memory.

if(*x)
Undefined Behavior.

The program can do anything here.

You're referencing memory -- what x points to -- that hasn't been
initialized.

Anyway in standard C++ the 'if' will not be executed if the allocation
fails.

If the allocation fails you get a std::bad_alloc exception, not a null
pointer.
strcpy(x,y);
Use std::string instead.

else
{
cout<<"value at x\t"<<x<<endl;
cout<<y<<endl;//checkig formal
parameter
Pass that information via the exception, e.g. a std::runtime_er ror, instead
of doing i/o down in your classes.

throw 1;
Use standard exception classes.

}
}catch(...){
cout<<"Construc tor B(char *y=3D\"xxx\") "<<endl;
cout<<"memory allocation failure"<<endl;
Here you forgot to rethrow the exception, which means the calling code may
go on to use a B-object that isn't really usable.

Add:

throw;

}
}

[snip]
main()


'main' must have result type 'int'.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 26 '05 #2

"kk" <ki**********@g mail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
Hi all,
i didn't get output in the following code while compiling and executing
with g++ version 3.2.3 it doesn't allocate memory to pointer varaible
(x) in class B. and it gives correct output while executing in .Net and
visual slick editor. why it didn't allocate memory? if anybody knows
plz give reply.
thanks in advance

kk

------File Name: les9_5.C--------------
#include <iostream>
#include <string.h>
using namespace std;
class B{
char *x;
public:
B(char *y="xxx"):x(ne w char[strlen(y)+1]){
try{
// x=new char[strlen(y)+1];

A few things:

1) you've commented out the allocation above, and replaced it with an
initializer list. Why put the "new" in the initializer, but keep this
useless code below which checks if x is allocated or not? In a conforming
compiler, new throws an exception if it fails. Why do you want all this
code below? If the exception happens, it will happen in the initializer
list above, before you enter the try, where you actually _could_ catch it.

2) Why are you BOTH checking if the pointer is nil AND trying
(unsuccessfully ) to catch the allocation exception? Remove the if statement
test.

3) What if y is nil? Your code should probably be testing if y is nil (not
if x is nil), and if it's not, THEN allocate memory for x and copy y to it.
(Otherswise I assume x should be nil?)

4) Suppose in your code that you did catch an exception somehow. You're
allowing the constructor to continue, reporting via cout that an error
occurred. But there's still a problem, in that x was never properly
allocated. How's the rest of your program going to like that? If you want
to report an exception via cout, that's fine, but you need to be sure you
either re-throw the exception or else take some appropriate action to make
sure your object is in a viable state.

if(*x)
strcpy(x,y);
else
{
cout<<"value at x\t"<<x<<endl;
cout<<y<<endl;//checkig formal
parameter
throw 1;
}
}catch(...){
cout<<"Construc tor B(char *y=\"xxx\") "<<endl;
cout<<"memory allocation failure"<<endl;
}
}

-Howard
Jul 26 '05 #3
kk wrote:
class B{
char *x;
public:
B(char *y="xxx"):x(ne w char[strlen(y)+1]){
try{

if(*x)


*x doesn't have a deterministic value. Even if the language
default initialized it, *x would be 0. I suspect you really
were trying to see do
if(x)
However, there is no way on a conforming compiler that the
value of your new expression would have returned a null
pointer. New as you have written it should throw bad_alloc
on failure.
Jul 26 '05 #4
Ron Natalie wrote:
New as you have written it should throw bad_alloc
on failure.


I suspect OP is using VC6, based on an earlier discussion thread.
Jul 26 '05 #5

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

Similar topics

2
5350
by: hall | last post by:
I have a question regarding where memory is allocated when arrays are created. I'll illustrate this by example. I may be wrong on some details, do feel free to correct me. The code piece: int p; Creates a 2dimensional array. p can be thought of as a pointer, containing the adres of the first element in the array. The memory is
8
6863
by: Tron Thomas | last post by:
As part of applying for a programming position at a company, I recently I had submitted some code samples to one of the developers for review. This is the feedback I received: One of his concerns was frequent calls to new and delete, which can cause memory fragmentation over time. An example is the allocation and destruction
32
3866
by: John | last post by:
Hi all: When I run my code, I find that the memory that the code uses keeps increasing. I have a PC with 2G RAM running Debian linux. The code consumes 1.5G memory by the time it finishes execution. But I do not think it needs so much memory. About 500M memory should be enough. I have following questions about memory leak. (1).If in my code I only define constructor for my class, and do not define destructor, will it cause memory leak?
22
3489
by: xixi | last post by:
hi, we are using db2 udb v8.1 for windows, i have changed the buffer pool size to accommadate better performance, say size 200000, if i have multiple connection to the same database from application server, will each connection take the memory 800M (200000 x 4k = 800 M), so the memory took will be 800M times number of connections, or the total memory get from bufferpool will be 800M?
14
20787
by: Alessandro Monopoli | last post by:
Hi all, I'm searching a PORTABLE way to get the available and total physical memory. Something like "getTotalMemory" and it returns the memory installed on my PC in bytes, and "getAvailableMemory" and it returns the available memory in bytes. Do you know is there's a C function, a c++ Object or anything else that compiles in Linux and Windows to get these data?
10
14062
by: eyh5 | last post by:
Hi, My C code (running on Soalris Unix) has some "segmentation fault" that I wish to use purify to do it. I poked around the web, and found some information about adding some lines in a Makefile file to use purify. However, my code is a rather simple single-source C program, and I didn't write a Makefile for it. I'm wondering if anybody can tell me which commands are to be entered at the Unix prompt to use purify. And, I don't know if...
4
3434
by: Hermann Maier | last post by:
hi, i need to find out the memory usage of a specific function that i use in my program. this function does some recursive calculations and i want my program to display the amount of memory the function used to calculate a specific value. thx
74
4708
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
19
1696
by: smarty | last post by:
how can I find the memory allocated dynamically? is there any possibility of finding it?
50
3523
by: arunajob | last post by:
Hi all, If I have a piece of code something like this void main(void) { char * p1="abcdefghijklmn"; ............................................. }
0
9704
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
9569
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
10558
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
10318
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
10302
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
10069
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...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5503
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...
1
4277
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

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.