Quick C++ question on pointers

Started by
14 comments, last by Ubermeowmix 9 years, 4 months ago

Can anyone help with pointers in functions?

When I declare a pointer in a function outside of main:


void aFunction()
{
    SomethingClass *current = NULL;   
}

int main()
{
    aFunction();
}

When this is called what happens to the pointer, obviously assuming that I have created a class as well.

Do I need to delete this pointer, is it left as a dangling pointer on close? Or is it only when the 'new' keyword is used?

If you get near a point, make it!
Advertisement
If you allocated anything using new, you have to delete it later (either directly or by using a smart pointer like for example std::unique_ptr or std::shared_ptr), otherwise it leaks. Whether or not a pointer is involved is irrelevant. You can use new without explicit pointers and you can use pointers without using new.

First of all, you need to consider the scope of functions. When a function is executed, most of the things defined inside the funciton's body lives until the function ends. Most variables are stored in the stack unless you allocate them in heap memory (with any method). The stack memory is freed when the function ends, the heap don't.

On the other hand, you need to understand that a pointer and the object it points probably live in different memory (the pointer in the stack, the pointed object in the heap). The pointer is a value, the memory address of the allocated object. That value (the address) is lost when the function ends, that's why you need to free the memory before finishing the function, or you need to return the address, otherwise you'll lose all references to that object.

In case you return the address, you're returning the value, not the variable itself (remember, the "current" variable will dissapear). This is the same that happens if you return an int for example, you may store the int temporarily in an internal function variable, but when you return it, you're actually returning the value, not the variable.

If you declare the pointer but don't create a new instance of the class (i.e. "= NULL;" like you wrote), there's no memory to free, the pointer itself is in the stack so the few bytes of memory it took are managed by the system.

Also, you should look at the smart pointers BitMaster named, they'll help you with this stuff and make things more explicit.

In the example you provided, 'current' is going to be a stack allocation - so you won't need to clean it up.

If you did something like this :


void aFunction()
{
 SomethingClass* current = new SomethingClass();
}

Then then a chunk of memory on the heap would be allocated, and the variable 'current' would point to it. The variable 'current' is still allocated on the stack, it just points to memory that's located in the heap.

Because the above code doesn't explicitly free up the memory in the heap (by calling 'delete current') you'd have a memory leak each time you call that function.

Following on from that situation, why can't I do the following?


#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

class MyClass
{
    int _health;
    string _name;
public:
    MyClass() : _health(10), _name("John Doe") {}
    MyClass(int h, string n) : _health(h), _name(n) {}
    ~MyClass(){}

    int fReturnHealth() { return _health; }
    string fReturnName() { return _name; }

    void fAlterHealth(int h) { _health = h; }
    void fAlterName(string n) { _name = n; }
};

class ChangeChar
{
public:
    ChangeChar(){}

    void fChangeHealth(MyClass *myChar, int h) { myChar->fAlterHealth(h); }
    void fChangeName(MyClass *myChar, string n) { myChar->fAlterName(n); }
};

int main()
{
    MyClass newChar;
    MyClass newChar2(20, "Paul");

    ChangeChar alterMyChar;

    cout << "newChar: " << newChar.fReturnHealth() << endl;
    cout << "newChar: " << newChar.fReturnName() << endl;

    cout << "newChar2: " << newChar2.fReturnHealth() << endl;
    cout << "newChar2: " << newChar2.fReturnName() << endl;

    alterMyChar.fChangeHealth(newChar2, 15);
    alterMyChar.fChangeName(newChar2, "Timmy");

    cout << "newChar2: " << newChar2.fReturnHealth() << endl;
    cout << "newChar2: " << newChar2.fReturnName() << endl;

    return 0;
}

If you get near a point, make it!

What exactly can't you do? Is there a compilation error or the output is not what you expect?

Yeah it's crashing!

Just noticed that I wasn't passing a pointer:

MyClass* newChar;

and that was causing part of the issue, but now I have a random const char* error!?

cannot convert 'const char*' to 'MyClass*' in initialization

I haven't declared a const char*???

If you get near a point, make it!
It sounds like you changed your code since the last time you posted it. Can you post some piece of code and a clear description of what the problem is?

I'll try to help you, even though your code seems to be affected by the former-Java-programmer disease. smile.png

Just glancing throught this thread... but:


cannot convert 'const char*' to 'MyClass*' in initialization

You have not initialised the pointer.

Todo so you need to do:


   MyClass * newChar;
   newChar = new MyClass(arg1, "arg2");

//.... Now you can use newChar's members

Edit:

Just looked back at your code, I noticed that newChar and NewChar2 are non pointer objects, but you use them as pointers in: ChangeChar class. If you change them to pointers (as the code above) it should work.

--Sorry not much time to go indepth, hope this helps/correct

Mobile Developer at PawPrint Games ltd.

(Not "mobile" as in I move around a lot, but as in phones, mobile phone developer)

(Although I am mobile. no, not as in a babies mobile, I move from place to place)

(Not "place" as in fish, but location.)

It sounds like you changed your code since the last time you posted it. Can you post some piece of code and a clear description of what the problem is?

I'll try to help you, even though your code seems to be affected by the former-Java-programmer disease. smile.png

LOL my roots were in javascript and actionscript so it's been a rocky transition at best, the only advantage I had was some early Visual Basic at college to help me along.

If you get near a point, make it!

This topic is closed to new replies.

Advertisement