Returning pointers and memory problems

Hi
I've a question about returning pointers from functions.
I know it isnt properly a C++ question, but I've doubts with C++ classes too.

First of all, if this code is wrong:

1
2
3
4
5
char *itoa(int n) {
    char retbuf[25];
    sprintf(retbuf, "%d", n);
    return retbuf;
}


Why this should be right:

1
2
3
4
5
6
7
char *itoa(int n) {
    char *retbuf = malloc(25);
    if(retbuf == NULL)
        return NULL;
    sprintf(retbuf, "%d", n);
    return retbuf;
}


Isnt it another temporarly char pointer declared in function call space (in stack) ?
I know the "content" of variable is stored in heap, but it returns an "address number" and is it temporarly or not ?

and if i've this class:

1
2
3
4
5
6
7
8
9
class B {
    protected:
        std::string *a;
    public:
        B (const char *str) { a = new std::string (str); return; }
        std::string *getA() {
            return a;
        }
};


Is getA code right in terms of memory ?

Thanks :)
Last edited on
In the first function a static array is created. It will no longer exist after the function ends (other functions may be using the same memory then). Therefore returning a pointer to this array is useless.
In the second one, malloc creates an array on the heap. This array will stay there until you free it. While retbuf is temporary, it is only the address of this array. It will be copied to whatever you assign itoa() to.

getA is ok. You of course should still check if it doesn't return 0. I'm not really sure what exactly is not clear here..
closed account (3pj6b7Xj)
If you make a function that returns a pointer, remember, a pointer is an address in memory, a location, therefor you can not simply say return retbuf; that is incorrect, you must return the address of retbuf instead, ASSUMING IT IS STILL IN MEMORY!!! return &retbuf;
mrfaosfx, you are wrong. when you have an array, for example int arr[50]; the type of arr is int*.
ty :)
Topic archived. No new replies allowed.