Question

I couldn't believe that I couldn't get this right! Someone please help! This says word is being used without being initialised(Is that required?):

int main(int argc, char* argv[])
{
    char* word;
    sprintf(word,"%d",12);
    std::cout << word;

    return 0;
}

And if I were to do this, it gives DEBUG ASSERTION FAILED!:

int main(int argc, char* argv[])
{
    char* word = NULL; // char* word = nullptr;
    sprintf(word,"%d",12);
    std::cout << word;

    return 0;
}

I have included stdio.h header. It is not making sense how I am fumbling over this.

Was it helpful?

Solution

You need to initialize it with allocated memory.

char word[20];

or

char* word = new char[20];

Initializing it to NULL will make it crash as the function tries to write at this address. Not initializing it will be undefined behavior as well since the address will be garbage.

OTHER TIPS

Both those code snippets are undefined behavior.

In the first, the pointer word is uninitialized, so its value is indeterminate (and will seem to be random), so when using to write data you don't know where it will be written.

The second will always write to address zero, which is also undefined behavior.


The solution to this is to remember that you are using C++, which have std::string:

std::string word;
word = "12";

Or if you have the number as an integer that you want to use, then look at std::ostringstream:

int value = 12;

// ...

std::ostringstream os;
os << value;

std::string word = os.str();

You are declaring word as a pointer: to what? If you need a string, and you still want to use sprintf, you have to declare its length:

char word[20]; // twenty bytes including string terminator \0

This fixed-length syntax is prone to errors and nowadays obsolete: please refer to @Joachim Pileborg answer for a better use of strings in C++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top