-2

I write a function to return IP address in C++, as I am new to C++ so I want to make my code proficient. I knew to create a new variable needs new, and we need to delete it.

I do not know why char *hostbuffer = new char[1024](); is not as same as char hostbuffer[1024]={0}, both of them are creating a size 1024 int array, right?

std::string ipfunction_Client(){

    char *hostbuffer = new char[1024]();---This cannot work
    //char hostbuffer[1024]={0};---This can work
    char *IPbuffer=new char[1024];
    struct hostent *host_entry;

    gethostname(hostbuffer,sizeof(hostbuffer));

    host_entry=gethostbyname(hostbuffer);

    IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));-----This is client.cpp 230
    //delete(hostbuffer);
    return std::string(IPbuffer);
}

If I use the above code, the valgrind's feed back is this:

Process terminating with default action of signal 11 (SIGSEGV): dumping core
==19697==  Access not within mapped region at address 0x18
==19697==    at 0x406624: ipfunction_Client() (client.cpp:230)
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jambako
  • 73
  • 1
  • 6

1 Answers1

4

When you use

char *hostbuffer = new char[1024]();

sizeof(hostbuffer) evaluates to the size of a pointer, not the size of the array.

When you use

char hostbuffer[1024]={0};

sizeof(hostbuffer) evaluates to the size of the array.

The call

gethostname(hostbuffer,sizeof(hostbuffer));

will work differently based on the declaration you use.

That's the most significant difference in your code.

If you use

const int BUFFER_SIZE = 1024;
char *hostbuffer = new char[BUFFER_SIZE]();

...

gethostname(hostbuffer, BUFFER_SIZE);

you should not see any difference in behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    Using all uppercase identifiers for constants became really bad habit. – Slava Oct 02 '19 at 17:10
  • @Slava, guilty as charged. – R Sahu Oct 02 '19 at 17:12
  • 1
    It actually bit me once, enum from somebody else code and macro from third party C library, catching it was not pleaseant though it produced compilation error. If it would not - God help he catching the bug. – Slava Oct 02 '19 at 17:16
  • Thank you, these really help me. – Jambako Oct 02 '19 at 17:19
  • @Slava, I once ran into the `class Object` from two third party libraries whose headers needed to be `#include`d in one .cpp file. Fun, fun. – R Sahu Oct 02 '19 at 17:19
  • @Jambako, glad I was able to help. – R Sahu Oct 02 '19 at 17:20
  • 1
    Name collision at least does not compile, with those pesky identifiers it is really good chance it would. That would be a disaster. – Slava Oct 02 '19 at 17:22