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)