allocating zero bytes

S

Serve Laurijssen

char *s = new(std::nothrow) char[0];

std::cout << (void *)s << std::endl;

On my machine the value of s does not equal NULL. What does the standard say
about that?
 
P

peter koch

 char *s = new(std::nothrow) char[0];

 std::cout << (void *)s << std::endl;

On my machine the value of s does not equal NULL. What does the standard say
about that?

This is fine and defined. Remember to delete [] when you have finished
using the pointer. I assume you are on an embedded platform doing
this? I would normally expect std::vector or std::string to be better
for this (calling terminate if the allocation should fail).

/Peter
 
S

Serve Laurijssen

"peter koch" <[email protected]> schreef in bericht
char *s = new(std::nothrow) char[0];

std::cout << (void *)s << std::endl;

On my machine the value of s does not equal NULL. What does the standard
say
about that?

This is fine and defined. Remember to delete [] when you have finished
using the pointer. I assume you are on an embedded platform doing
this? I would normally expect std::vector or std::string to be better
for this (calling terminate if the allocation should fail).

After allocating zero, is the following UB then?

std::cout << *s << std::endl;
 
J

Jack Klein

"peter koch" <[email protected]> schreef in bericht
char *s = new(std::nothrow) char[0];

std::cout << (void *)s << std::endl;

On my machine the value of s does not equal NULL. What does the standard
say
about that?

This is fine and defined. Remember to delete [] when you have finished
using the pointer. I assume you are on an embedded platform doing
this? I would normally expect std::vector or std::string to be better
for this (calling terminate if the allocation should fail).

After allocating zero, is the following UB then?

std::cout << *s << std::endl;

Please find the setting in your Windows Mail program to properly quote
material in your reply. Thank you.

As to your follow-up question, yes, it is undefined behavior. There
are exactly 0 bytes that you may access through that pointer, which is
exactly what you asked for.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top