George Dunbar
George Dunbar

Reputation: 21

String not storing in a structure properly

typedef struct class {
   char* CLASS_ID;
   char* CLASS_NAME;
}

What would cause those two strings to lose their values over the course of 30-40 unrelated lines of code? (Assigned to a pointer returned from a function called getString()).

Upvotes: 1

Views: 218

Answers (3)

Bernd Elkemann
Bernd Elkemann

Reputation: 23560

Aside from what the other's posted here there's also that you should avoid names like class, CLASS_ID and CLASS_NAME because they are #defined in many librarys you might include in the future and debug for hours to find out what's suddenly wrong.

Upvotes: 0

Nick Meyer
Nick Meyer

Reputation: 40412

Perhaps getString() returns a pointer to a statically allocated buffer, whose value is overwritten each time it is called?

Maybe you're overflowing an array and corrupting your stack or heap?

Maybe you're storing a pointer to a string that was allocated on the stack and has gone out of scope?

With some more information about or code for getString(), someone could probably give you a definitive answer.

Upvotes: 2

T.E.D.
T.E.D.

Reputation: 44814

Well, not knowing how getString() is implemented, or any of your other code, it could be anything. That is part of the problem with C's (over)use of pointers.

My first guess would be that getString() actually returns a pointer to an internal (static) string, and thus each call obliterates the value retrieved from the last.

If you are actually using C++, then I would strongly advise you to ditch this code and use std::string instead. I bet your problem magically goes away.

Upvotes: 1

Related Questions