开发者

Having issues with initializing character array

Ok, this is for homework about hashtables, but this is the simple stuff I thought I was able to do from ea开发者_如何转开发rlier classes, and I'm tearing my hair out. The professor is not being responsive enough, so I thought I'd try here.

We have a hashtable of stock objects.The stock objects are created like so:

stock("IBM", "International Business Machines", 2573, date(date::MAY, 23, 1967))

my constructor looks like:

stock::stock(char const * const symbol, char const * const name, int sharePrice, date priceDate): m_symbol(NULL), m_name(NULL), sharePrice(sharePrice), dateOfPrice(priceDate)
{    
setSymbol(symbol);
setName(name);
}

and setSymbol looks like this: (setName is indentical):

void stock::setSymbol(const char* symbol)  
{  
if (m_symbol)  
    delete [] m_symbol;  
m_symbol = new char[strlen(symbol)+1];  
strcpy(m_symbol,symbol);  
}  

and it refuses to allocate on the line

m_symbol = new char[strlen(symbol)+1];

with a std::bad_alloc. name and symbol are declared

char * m_name;  
char * m_symbol;

It's definitely strlen() that is going astray. And it doesn't seem to happen every time.

cout << symbol << strlen(symbol); 

returns IBM correctly, then crashes


As this is tagged C++ can you use std::string instead of doing all the pointer maintenance yourself on char*?

std::string name;
std::string symbol

Then setSymbol becomes easy:

void stock::setSymbol(const char* symbol)  
{
    this->symbol = symbol;
}


There must be some problem with symbol parameter at the time you call

new char[strlen(symbol)+1];

and strlen return a huge length that C++ runtime is unable to allocate. If symbol is uninitialized char* pointer at the beginning this is fairly possible. It doesn't fail all the time, does it?


I was able to run the code without problems on Cygwin, so I'd guess it's something implementation-dependent in distinguishing the parameter symbol from the member symbol.

You say yourself that it's confusing -- well do something about it!!! And may I suggest, never, ever again, naming a parameter the same as a local/member variable. (Not only does it eliminate confusion, you won't need to disambiguate the member variable with this->.)


Thanks to everyone who offered help. I went over it with my professor, and unfortunately I was overflowing an array earlier and corrupting the heap, which was manifesting itself here.

This was a good conversation for me though. It helped me think through some things I had just been doing. So thanks again SO'ers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜