About pointers

1
2
3
4
void* Func(){
void* local;
return local;
}

This code is safe?
local variable is deleted on end of function
 
void* pointer = Func(); //where is the local variable?? 

Last edited on
It is safe as long as you don't delete the memory local is pointing to. In your simplified example, you don't make local point anywhere, so it really is useless. Maybe a more complete example is in order:

1
2
3
4
5
6
7
8
9
10
11
12
void *Func1()
{
    void *local = new char[256];
    return local; //Correct.  The newly allocated array of chars won't be deleted on return.
}

void *Func2()
{
    char myString[256];
    strcpy(myString, "Test string....");
    return (void*)myString; //Incorrect:  myString is a local array that will be destroyed once the function returns.
}
Last edited on
Thanks for reply.

Your examples are better to understand.
RE: webJose

So, How to delete dynamically-allocated memory from Func1?
Last edited on
The example is intended to show only how it would be safe to return a pointer, but in reality is not good practice.

To answer the question, the caller of Func1() would save the pointer, use it somehow, and finally call delete[] on it.

But the good practice is: Instead of Func1() allocating memory in behalf of the caller, the caller itself should allocate the memory, pass the allocated pointer to Func1(), Func1() would do whatever it needs to do, and finally, after the call, it is understood that the buffer now contains useful data as a result of calling Func1().
Also note that void pointers are not typesafe.

void pointers and new/delete especially don't play nice together.
Topic archived. No new replies allowed.