473,486 Members | 1,560 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

The new operator

Hi all,
I was wondering how the program below was working. I
overloaded the new operator, which is responsible for allocating memory
for the object. But I made an explicit memory allocation [ zero bytes
]. When the object was created, somehow the value was assigned
correctly and it prints the correct result. How is this possible ???

# include <iostream>

using namespace std;

class A
{
long a;
public:
A(long x) { a=x; }
long getA(){return this->a;}
void* operator new (size_t);
void operator delete (void *);
};

void* A::operator new (size_t size)
{
void *ptr = malloc(0);
return ptr;
}

void A::operator delete (void *p)
{
free(p);
}

int main()
{
A *a=new A(1234567);
cout << a->getA() << endl;
delete a;
return 0;
}

Aug 9 '06 #1
7 1507
sarathy wrote:
Hi all,
I was wondering how the program below was working. I
overloaded the new operator, which is responsible for allocating memory
for the object. But I made an explicit memory allocation [ zero bytes
]. When the object was created, somehow the value was assigned
correctly and it prints the correct result. How is this possible ???

# include <iostream>

using namespace std;

class A
{
long a;
public:
A(long x) { a=x; }
long getA(){return this->a;}
void* operator new (size_t);
void operator delete (void *);
};

void* A::operator new (size_t size)
{
void *ptr = malloc(0);
return ptr;
}

void A::operator delete (void *p)
{
free(p);
}

int main()
{
A *a=new A(1234567);
cout << a->getA() << endl;
delete a;
return 0;
}
What you have is undefined behavior, which means anything could happen,
including appearing to "work" correctly.

--
Alan Johnson
Aug 9 '06 #2
"sarathy" <sp*********@gmail.comwrote in message
news:11*********************@h48g2000cwc.googlegro ups.com
Hi all,
I was wondering how the program below was working. I
overloaded the new operator, which is responsible for allocating
memory for the object. But I made an explicit memory allocation [
zero bytes ]. When the object was created, somehow the value was
assigned correctly and it prints the correct result. How is this
possible ???
I believe that the result of a malloc call with a zero argument is
implementation defined. malloc can either return a NULL pointer or it can
return a unique pointer to a zero amount of memory. The VC++ docs say this
about malloc:

"If size is 0, malloc allocates a zero-length item in the heap and returns a
valid pointer to that item."

See below.

# include <iostream>

using namespace std;

class A
{
long a;
public:
A(long x) { a=x; }
long getA(){return this->a;}
void* operator new (size_t);
void operator delete (void *);
};

void* A::operator new (size_t size)
{
void *ptr = malloc(0);
return ptr;
}

void A::operator delete (void *p)
{
free(p);
}

int main()
{
A *a=new A(1234567);
Pointer a ends up pointing somewhere on the heap and then the constructor
writes an A object to the memory that a points to. Because a zero amount of
memory has been allocated, this involves writing on memory that hasn't been
allocated for the purpose, so your application is likely to crash or
otherwise misbehave. However, it may behave well enough for the constructor
to write the integer to A's member variable and for getA() to retrieve it.
cout << a->getA() << endl;
delete a;
return 0;
}

--
John Carson


Aug 9 '06 #3
John Carson wrote:
I believe that the result of a malloc call with a zero argument is
implementation defined. malloc can either return a NULL pointer or it can
return a unique pointer to a zero amount of memory. The VC++ docs say this
about malloc:

"If size is 0, malloc allocates a zero-length item in the heap and returns a
valid pointer to that item."
Which is what the standard says. It's not implementation defined. An
implementation that returns zero to malloc(0) is non-standard.
Aug 11 '06 #4
"Ron Natalie" <ro*@spamcop.netwrote in message
news:44***********************@news.newshosting.co m
John Carson wrote:
>I believe that the result of a malloc call with a zero argument is
implementation defined. malloc can either return a NULL pointer or
it can return a unique pointer to a zero amount of memory. The VC++
docs say this about malloc:

"If size is 0, malloc allocates a zero-length item in the heap and
returns a valid pointer to that item."

Which is what the standard says. It's not implementation defined. An
implementation that returns zero to malloc(0) is non-standard.

I am sceptical of this. I can't find anything in the C++ Standard that says
it (and the C standard definitely makes the behaviour implementation
dependent). Further, typing in malloc(0) in Google Groups for this newsgroup
and its moderated counterpart yields various threads in which knowledgeable
people make the same statement that I did or don't contradict other people
when they make the statement.

--
John Carson
Aug 11 '06 #5
John Carson <jc****************@netspace.net.auwrote:
"Ron Natalie" <ro*@spamcop.netwrote in message
news:44***********************@news.newshosting.co m
>John Carson wrote:
>>I believe that the result of a malloc call with a zero argument is
implementation defined. malloc can either return a NULL pointer or
it can return a unique pointer to a zero amount of memory. The VC++
docs say this about malloc:

"If size is 0, malloc allocates a zero-length item in the heap and
returns a valid pointer to that item."

Which is what the standard says. It's not implementation defined. An
implementation that returns zero to malloc(0) is non-standard.

I am sceptical of this. I can't find anything in the C++ Standard that says
it (and the C standard definitely makes the behaviour implementation
dependent). Further, typing in malloc(0) in Google Groups for this newsgroup
and its moderated counterpart yields various threads in which knowledgeable
people make the same statement that I did or don't contradict other people
when they make the statement.
I agree with John Carson, plus there is the entry in the C FAQ:

http://www.c-faq.com/ansi/malloc0.html

Q: What should malloc(0) do? Return a null pointer or a pointer to 0
bytes?

A: The ANSI/ISO Standard says that it may do either; the behavior is
implementation-defined (see question 11.33). Portable code must
either take care not to call malloc(0), or be prepared for the
possibility of a null return.

[Question 11.33 just defines the differences among
implementation-defined, unspecified, and undefined behavior]

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Aug 11 '06 #6
Ron Natalie wrote:
John Carson wrote:
I believe that the result of a malloc call with a zero argument is
implementation defined. malloc can either return a NULL pointer or
it can return a unique pointer to a zero amount of memory. The VC++
docs say this about malloc:

"If size is 0, malloc allocates a zero-length item in the heap and
returns a valid pointer to that item."

Which is what the standard says. It's not implementation defined.
An implementation that returns zero to malloc(0) is non-standard.

I don't think the C++ Standard says that, or much about malloc() at
all. It's a C library function, and behavior is controlled by the C
Standard. The C99 draft Standard says:

7.20.3 Memory management functions

[#1] The order and contiguity of storage allocated by
successive calls to the calloc, malloc, and realloc
functions is unspecified. The pointer returned if the
allocation succeeds is suitably aligned so that it may be
assigned to a pointer to any type of object and then used to
access such an object or an array of such objects in the
space allocated (until the space is explicitly freed or
reallocated). Each such allocation shall yield a pointer to
an object disjoint from any other object. The pointer
returned points to the start (lowest byte address) of the
allocated space. If the space cannot be allocated, a null
pointer is returned. If the size of the space requested is
zero, the behavior is implementation-defined: either a null
pointer is returned, or the behavior is as if the size were
some nonzero value, except that the returned pointer shall
not be used to access an object. The value of a pointer
that refers to freed space is indeterminate.

Naturally, there could be a change in the actual Standard, but I don't
believe so.

Brian

Aug 11 '06 #7
In article <44dcded5$0$17541$61c65585@un-2park-reader-
01.sydney.pipenetworks.com.au>, jc****************@netspace.net.au
says...

[ ... ]
I am sceptical of this. I can't find anything in the C++ Standard that says
it (and the C standard definitely makes the behaviour implementation
dependent). Further, typing in malloc(0) in Google Groups for this newsgroup
and its moderated counterpart yields various threads in which knowledgeable
people make the same statement that I did or don't contradict other people
when they make the statement.
You're right. The current version of C++ (i.e. the 2003 version) lists
C99 as a normative reference.

In C99 ($7.20.3) it says:

If the size of the space requested is zero, the behavior
is implementation-defined: either a null pointer is
returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not
be used to access an object.

The C++ requirements are covered in section 20.4.6:

3 The functions calloc(), malloc(), and realloc() do not
attempt to allocate storage by calling ::operator new()
(18.4).
4 The function free() does not attempt to deallocate
storage by calling ::operator delete().

So, in C++ (just as in C) malloc(0) can return either a null pointer, or
a some unique non-null pointer.

I suppose if somebody wanted to badly enough, they'd have some (minimal)
foundation for claiming ambiguity in C++ on this point though -- C++
2003 contains an inaccurate cross reference to the wrong section of the
C standard (to section 7.11.2 instead of 7.20.3, where the description
of malloc now lives).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 13 '06 #8

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

Similar topics

7
8015
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so...
1
3849
by: joesoap | last post by:
Hi can anybody please tell me what is wrong with my ostream operator??? this is the output i get using the 3 attached files. this is the output after i run assignment2 -joesoap #include...
5
3783
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more...
0
1816
by: Martin Magnusson | last post by:
I have defined a number of custom stream buffers with corresponding in and out streams for IO operations in my program, such as IO::output, IO::warning and IO::debug. Now, the debug stream should...
3
2927
by: Sensei | last post by:
Hi. I have a problem with a C++ code I can't resolve, or better, I can't see what the problem should be! Here's an excerpt of the incriminated code: === bspalgo.cpp // THAT'S THE BAD...
6
4398
by: YUY0x7 | last post by:
Hi, I am having a bit of trouble with a specialization of operator<<. Here goes: class MyStream { }; template <typename T> MyStream& operator<<(MyStream& lhs, T const &)
3
18784
by: gugdias | last post by:
I'm coding a simple matrix class, which is resulting in the following error when compiling with g++ 3.4.2 (mingw-special): * declaration of `operator/' as non-function * expected `;' before '<'...
5
2267
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
8
2471
by: valerij | last post by:
Yes, hi How to write "operator +" and "operator =" functions in a class with a defined constructor? The following code demonstrates that I don't really understand how to do it... I think it has...
3
3248
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
0
7094
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,...
0
6964
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...
0
7123
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,...
0
7173
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...
1
6839
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...
0
5427
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,...
1
4863
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...
0
4559
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...
0
3066
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...

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.