mardi 17 mars 2015

Array allocates space for more elements than requested


When I execute the following code, c_copy is initialized with more elements than specified by sz, what is causing this behavior? I thought that perhaps it was happening because arrays required a constant value, but declaring a constant value in or outside of the method did not help.



char* e4_strdup( const char*& c )
{
unsigned int sz{ 0 };
for ( const char* p_to_c = c; *p_to_c != '\0'; ++p_to_c )
++sz;

char* c_copy{ new char[ sz ] };
for ( unsigned int i{ 0 }; i < sz; ++i )
c_copy[ i ] = c[ i ];

return c_copy;
}



Aucun commentaire:

Enregistrer un commentaire