Init
Init

Reputation: 81

C++ variable used without initialization?

I am getting this error:

The variable "thename" is being used without being initialized

Here's my code:

char *thename;
cm++;
sprintf(thename, "tutmap%d.map", cm);

Upvotes: 0

Views: 5419

Answers (6)

Öö Tiib
Öö Tiib

Reputation: 10979

Instead of writing:

char *thename;
cm++;
sprintf(thename, "tutmap%d.map", cm);

Write:

cm++;
std::stringstream stream;     
stream << "tutmap" << cm << ".map";
std::string const name = stream.str();
// and if you really need char* then:
char const* thename = name.c_str();

Upvotes: 1

Fred Nurk
Fred Nurk

Reputation: 14212

You are using the variable without initializing it, and running this code will be Undefined Behavior.

Perhaps you meant:

char thename[42];
cm++;
sprintf(thename, "tutmap%d.map", cm);

If you have snprintf, here's a function which documents that you guarantee ("assert") the buffer to be large enough, but then also checks the buffer length and aborts if you made an error:

template<int N>
void fixed_sprintf(char (&array)[N], char const *format, ...) {
  va_list args;
  va_start(args, format);
  int used = vsnprintf(array, N, format, args);
  va_end(args);
  if (used == N - 1) {
    throw whatever_exception_type_you_like("buffer too small");
    // or even:
    abort();
  }
}

The "fixed" means "fixed-size", not "opposite of broken". :)

Upvotes: 8

Farshid Zaker
Farshid Zaker

Reputation: 1990

char *thename = new char[21]; //21 is used for maximum string length of 20
cm++;
sprintf(thename, "tutmap%d.map", cm);

Upvotes: 0

user2100815
user2100815

Reputation:

It's pretty easy to understand:

char *thename;

does not initialise thename, and then:

sprintf(thename, "tutmap%d.map", cm);

uses it. With dire results, in this case.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612834

You've declared a pointer to a C string but not allocated any memory for it.

If you want stack allocated memory use

char thename[buffer_length];

If you prefer heap allocation use

char *thename = malloc(buffer_length);

I know the question is tagged C++ but your code looks more like C to me. Hence the use of malloc.

Upvotes: 2

Sandeep
Sandeep

Reputation: 658

thename is a pointer that has not been initialized. Change thename to an array of char that will fit the size of the complete string generated by sprintf.

Upvotes: 0

Related Questions