As the title says, my class is returning garbage strings and I can’t figure out where the problem is. Note that this code is C with Classes, so the code has some C++ features, but specifically no namespaces (i.e. no std::string).
I did search the Q&A before posting, but most of the other Qs are assuming a more modern implementation of the language.
class definition file:
#ifndef SOFTWARE_HPP
#define SOFTWARE_HPP 1
#include <stdlib.h>
#include <string.h>
class Software
{
char* name;
public:
Software( void );
Software( const char* Name );
~Software( void );
void Name( const char* Name );
char* Name( void ) const;
};
void GetSoftware( Software* (&software)[], const unsigned short ArraySize );
#endif
Class implementation file:
#include "software.hpp"
const unsigned short _MAX_SOFTWARE_NAME = 21;
Software::Software( void )
{
name = new char[_MAX_SOFTWARE_NAME + 1];
name[0] = NULL;
}
Software::Software( const char* Name )
{
name = new char[_MAX_SOFTWARE_NAME + 1];
strncpy( name, Name, _MAX_SOFTWARE_NAME );
}
Software::~Software( void )
{
delete[] name;
}
void Software::Name( const char* Name )
{
if ( strlen( Name ) < _MAX_SOFTWARE_NAME ) {
strncpy( name, Name, _MAX_SOFTWARE_NAME );
}
}
char* Software::Name( void ) const
{
return name;
}
void GetSoftware( Software* (&software)[], const unsigned short ArraySize )
{
for ( short i = 0; i < ArraySize; ++i ) {
software[i] = new Software( "SoftwareName" );
}
}
Then in my main program:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "software.hpp"
int main( int argc, char* argv[] )
{
Software* software[16] = { NULL };
GetSoftware( software, 16 );
for ( int i = 0; i < sizeof( software ) / sizeof( software[0] ); ++i ) {
printf( "Software %s", software[i]->Name() );
}
}
So if I’m doing this right, I’m passing in my array of objects by reference. If I printf
the Software::Name
from the implementation file, the characters are fine. But when I try to output the string from the main()
function, I get a bunch of garbage characters.
One interesting note is that if I run my application from my Windows NT development machine, the characters print out fine, but when run under true DOS is when I get the garbles.
This is a medium memory model project, btw. Any ideas what I’m doing wrong?