简体   繁体   中英

Did a static variable is global variable?

I have two questions in C++.

First, is a global variable the same thing as a static variable? What is particular about a static variable?

Secondly, I actually code a project and if I do not use static variable, my code sent me the next error :

Run-Time Check Failure #2 - Stack around the variable 'szData' was corrupted.

This error appear due to sprintf, because I remove it and all is ok..

bool CreateFile(MyCards** ppCards)
{
    fstream ficCar;
    static char szData[31];
    ficEmployes.open("./my_cards.dat", ios::in | ios::binary);

    if (!ficCar.fail())
    {
        ficCar.close();
        return false;
    }
    else
    {
        sort(ppCards, ppCards + 26271, OrderedCards); 
        ppCards.open("./nom_cartes.index", ios::out | ios::binary);

        if (ficCar.fail())
        {
            throw "Error";
        }
        else
        {

            for (int indice = 0; indice < 10123; indice++)
            {
                sprintf(szData, "%-20s %010d \n",
                    ppCards[indice]->GetNom(),
                    ppCards[indice]->GetPosition());

                ficCar.write(szEnregistrement, 30);

            }

            ficCar.close();

            return true;
        }
    }

}

Anyone can help me? Thanks!

static variable does not equal to global, static variable can have scope: within compilation unit, function, class.

For question #2, szData has 31 bytes but sprintf try to put more on it, so it corrupt things nearby. Even you make it static, it will corrupt something else.

An object declared at namespace scope is static , and that makes it "global" in a sense.

An object declared in a function and marked static could sort of be called a "global" due to the way its scope behaves, but it cannot be accessed from outside the function.

For this reason, you'd be better off avoiding the term "global" and sticking with standard C++ terminology that is precise.

As for your code fault, you're trying to put more than 31 characters into an array of 31 characters. That's just not going to go well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM