C++ Check if pointer is passed, else create one? - c++

Okay i've seen this done somewhere before where you have a function that takes a pointer parameter and returns a pointer.
However you can choose not to pass a parameter and it will return a dynamically allocated pointer but if you do pass a pointer then it just fills it in instead of creating one on the heap. This is a single function not overloaded.
My question is how is this safely done?
I had a guess it was something like this:
point* funct(point *p = some_value)
{
if p == some_value
//create a point *p on the heap
else
//create use the given *p and fill it in
return p
}
Now i can't think if this is right way to do it and if it is then what could be a good some_value? it can't be NULL because when you pass empty pointer it will also be NULL and not sure if it is safe to have it greater than 0. Also you can't have negative numbers on pointers either, so whats a good safe value?
Any good way to do this that is also PORTABLE across platforms?
EDIT:
Okay maybe i didn't explain properly basically i want the function to be used like this:
point *x;
point *y;
x = func();
func(y);
Not
x = func(NULL);
if I use NULL i get an error segmentation fault only when i do func(y);
The reason for this is:
either the user passes a pointer he manages such as one created on the stack OR the function will give a dynamic one back if none is given. I don't want to force the return of only dynamic memory or only accepting a pointer to fill.
I know I have seen this done somewhere before.

Normal solution is to have 'if NULL allocate' - that's what 'c' realloc does.
It looks like you want to have a function that uses existing memory if provided or else allocates it's own.
It's not clear what you should return if you are passed a valid pointer.
Should it return that pointer?
Or should it be null to ensure that there aren't two copies of pointers to the same bit of memory - which will cause problems if they are freed.
It might be safer to pass a **pointer into the function and require an argument - even if that arguement is a pointer to null.

Well obviously if a someone ever was to call funct(NULL) then it would result in a crash anyway. so why not have some_value=NULL so to make
if(p==NULL){
p=dynamic_memory;
}
where dynamic_memory is allocated in the constructor(not thread-safe!) or replace dynamic_memory with a call to new
Edit:
Or. If you must have 3 states in your function, one for if no argument is supplied, one for if a valid pointer is passed, and one for if NULL is passed, then you can use pointer-to-pointers.
like
void *func(void** p=NULL){
if(p==NULL) ...//user supplied no argument
if(*p==NULL) ...//user supplied NULL
else //user supplied valid pointer
This doesn't seem to be what you want however and then people would have to pass pointers with '&' to your function.. (is &NULL even valid?)

My guess would be more along the lines of:
point* funct(point *p = NULL)
{
if (p == NULL) {
// create a point *p on the heap
// and use it
return(p);
}
else {
//use the given *p and fill it in
return(NULL);
}
}
Not too sure about having the possibility of the pointer to your point object passed in though. Could be quite hard to check for, and checking the type of an object passed in, i.e. "looking under the covers" using RTTI, is not the best OO practice.

You get an error when you call func(y) because y is not initialized. It contains random bits that point to a random location in memory. You need to initialize y to NULL.
point *x, *y;
x = func();
y = NULL;
y = func(y); // so it can be deleted later you need to assign the return value
delete x;
delete y;
Why not do this? And avoid the heap allocation completely.
point x, y;
func(&x);
func(&y);
Or:
point *x;
point *y = new point();
x = func();
func(y);
delete x;
delete y;
As I said in the comment above, memory ownership is confusing in your function. Functions that dynamically allocate their results should do so every time or none of the time. When they do so some of the time, the potential for a memory leak is much higher.
Personally, I would go even further and avoid all allocations, pass by reference:
void func(point& p)
{
//do stuff
}
point x, y;
func(x);
func(y);

something like this:
T* func(T* p) {
if(!p) {
p = new T;
}
// do whatever with p
return p;
}
then you can either do:
T* x = func(NULL);
// whatever
delete x;
or:
T x;
func(&x);
EDIT:
There is a non-thread safe option which several libraries use. Basically it works like this:
T* func(T* p) {
static T buf;
if(!p) {
p = buf;
}
// do whatever with p
return p;
}
then you can either do:
T* p = func(NULL);
or:
T x;
T* p = func(&x);
There are often "reentrant" versions of these as well which are often tied to the non-thread safe versions like this:
T* func(T* p) {
// behaves as above example, except now we can
// use func_r in a thread safe way if we need to
static T buf;
return func_r(p, buf);
}
T* func_r(T* p, T *buf) {
if(!p) {
p = buf;
}
// do whatever with p
return p;
}

You have to ask yourself why passing NULL us giving you a seg-fault. It is certainly not because NULL is not an appropriate value, it will be caused by whatever your code does when NULL is passed. However you chose not to show that code.
Haver you stepped through this code in your debugger?
Apart from that, in C++ do not use NULL. It is a macro and open to incorrect redefinition. Use plain zero (0). The language places guarantees that a zero literal constant when converted to a pointer will not be a valid address. The chances are that your NULL macro is in fact defined as zero.
If you attempt to dereference a null pointer you will get a fault.

What's the problem with using NULL? That's the general way this is handled. If you really need to distinguish between "caller passed nothing" and "caller passed NULL", then use 0xFFFFFFFF on a 32-bit system or 0xFFFFFFFFFFFFFFFF on a 64-bit system.
point * funct(point * p = (point *)(-1))
{
if (p == (point *)(-1))
{
p = new point();
}
if (p == NULL)
{
// special case handling
return NULL;
}
// fill in p
return p
}
The '-1' cast will always be the maximum pointer value as long as you are on a two's-compliment architecture. Feel free to substitute the C-style cast with a reinterpret cast if you prefer.

You should pass it NULL (have null be default...) if you want to allocate, and pass an empty pointer if you want to fill in.
As jeffamaphone commented, there is a difference between an empty pointer and NULL, use your conditional statements to check if it is an empty pointer or NULL

However you can choose not to pass a parameter and it will return a dynamically allocated pointer but if you do pass a pointer then it just fills it in instead of creating one on the heap. This is a single function not overloaded.
Instead of using default arguments, you could overload the function:
point* funct(point *p = some_value)
{
// fills p
}
point* funct()
{
return funct(new point());
}
It might not be the right way but somewhere I think in the linux libraries there was a function that works exactly like above not sure how it is allocated internally though
I'm not aware of any such function. I would guess you're thinking of realloc which takes a pointer and a size_t and then decides whether to allocate memory, adjust already allocated memory, or free memory.
Now i can't think if this is right way to do it and if it is then what could be a good some_value? it can't be NULL because when you pass empty pointer it will also be NULL and not sure if it is safe to have it greater than 0. Also you can't have negative numbers on pointers either, so whats a good safe value?
I think your confusion comes from a fundamental misunderstanding of the NULL pointer.
Observe:
int x = 5;
int* px = &x;
int* p_null = NULL;
int* p;
int* p_new = new int();
px points to x, so it's not NULL. p_null begins life as NULL which means it doesn't point to anything.
I think you're using the term "empty pointer" to refer to something like p or p_new. However, although p doesn't point to a valid object it wasn't set to NULL either. It's effectively an invalid pointer, and there is no portable way to tell that it's invalid (on some machines it may be possible to tell if something is obviously not valid, but even then it's not possible to catch all invalid pointers -- see note -- and you probably don't want to anyway -- second half).
And p_new points to a valid address in dynamic memory. It's not NULL. It's not empty. In fact, new will initialize the int to 0.
In other words, NULL is the value you pass to functions that expect a pointer to tell them you don't have a pointer. That's what it is. And there isn't really the idea of an empty pointer. Dangling pointers (either uninitialized pointers, or pointers to memory that you don't have access to) aren't NULL, because if they were NULL they wouldn't dangle. And it's impossible to validate pointers in all cases to determine if they are valid.
NOTE
Consider:
int* p_new2 = new int();
delete p_new2;
delete does not set p_new2 to NULL. So after the delete, p_new2 will have an address in the correct range for a valid pointer (meaning that Windows' VirtualQuery method will say "sure, a pointer could point there"), but will not have permission to actually dereference that memory address.
NOTE 2
This is a terribly bad idea, don't do it:
int* funct()
{
int y = 5;
return &y;
}
int* x = funct();
y ceases to exist after funct() returns. So the the pointer to y that funct() hands you points to something that doesn't exist. So you get a dangling pointer. You're not talking about doing this, but it's a common mistake, and it will bite you.

Default value is what it is — default value. There's no such thing like not passing value here. It may only happen with variable parameters count, but that's different story.
And what is an "empty pointer"?

Are you looking for this:
point* funct(point *p = some_value)
{
if (p == NULL)
return NULL;
if (p == some_value)
p = new point;
return p;
}

Okay I've decided not to use that idiom seems bad although I know one of the unix or linux system libraries had a function like that.
I'm not answering my own question but I just remembered the ctime idiom which is probably a much safer way to do what I want. I'm talking about the time() function.
Where it takes a pointer or returns a object by value.
I think it probably even gives better flexibility of returning by value, heap or stack allocation with pointer thats user controlled. I don't know why I didn't think of this before.
What do you guys thing, the ctime idiom is much better right?
Edit: Does that idiom use NULL check?

If you really wish to split them in such a way you can't accidentally provide the default function, you ought ot overload the functions.
point* funct() {
//alocate a point* p here
return funct(p);
}
and
point* funct(point *p) {
//do stuff
}

Related

Passing the pointers by refrence?

**So recently i came up with a question in an interview it was based on pointers**
void fun(int *p){
int q = 10;
p = &q;
}
int main() {
int r = 20;
int *p = &r;
fun(p);
cout<<*p<<endl;
}
*my question is
(1)Justify the result w.r.t the memory allocation like how this is happening?;
(2) how to pass this pointer variable by refrence (i wrote *&p in the parameter of void fun()) when i did it i observed that the p is printing a garbage value ,Now first i thought may be fun has different memory allocation and when it takes the address of q from fun function it address changes but that address in main function is pointing to some garbage value ,Am i right and please explain?
void fun(int *&p) {
int q = 10;
// here the object q began its existence
p = &q;
// here you pass the address of that object *out*
// of the function, to the caller
// here the object q ceases to exist
// question: does anyone have now-invalid pointers that
// pointed to that object?
}
You'll of course immediately see that yes, the caller of fun has a pointer that doesn't point to a valid object (objects that don't exist are by definition invalid). This is undefined behavior. Anything can happen.
Whatever you observe is just as good as what anyone else would observe :) I can make this code pretend to work, or pretend fail on almost any compiler - it's only a matter of arranging things in a certain way. That doesn't make the code any more valid, of course, and the notion of "working" or "failing" is meaningless anyway: the code is invalid, so as far as C++ is concerned, the discussion about the effects is invalid as well :)

Pointer returns and scope

Is returning a pointer declared inside the function considered bad practice? Example:
int* foo(void)
{
int * ret_val = 1234;
return ret_val;
}
I believe you're suppose to use:
static int * ret_val = 1234;
But then again, wouldn't it still be considered bad practice to return memory outside of your scope?
Returning a pointer isn't a problem as long as it points to memory that is still in scope, such as dynamically allocated memory, global data, or local variables that still exist further up the call stack.
The problem with the above code is that you're dereferencing a pointer without assigning anything to it. This: *ret_val = 1234; assigns the value 1234 to the address that ret_val points to, but ret_val wasn't assigned anything.
If on the other hand you did this:
int* foo(void)
{
int * ret_val;
ret_val = malloc(sizeof(int));
*ret_val = 1234;
return ret_val;
}
That is fine since you're returning a pointer to dynamically allocated memory.
The primary culprit is
*ret_val = 1234;
is applied with an uninitialized pointer.
I believe you're suppose to use:
static int* ret_val;
No, to fix that you could use
int* foo() {
static int_val = 1234;
return &int_val;
}
But it's arguable if that's what you really want. All callers of that function will share the same instance of int_val.
It's a really bad practice if your return a pointer to a local variable, because you will have a dangling pointer.
int* foo(void)
{
int a = 1337;
return &a; //Don't do this!
}
But sometimes it could be useful:
int* copy_array(int *array, int size)
{
int *v = (int*) malloc (size * sizeof (int));
//..copy the array..
return v;
}
Anyway, you should avoid returning pointers, so there is no risk of memory leaks.
Aside from your use of ret_val without it being allocated, returning a pointer from a function is fair practice, though it takes special care:
Don't return a pointer to a local variable, as it will be destroyed when the function exits and cause undefined behavior if dereferenced
If the function allocates memory, it is the responsibility of the caller function to ensure that the pointer is deallocated when it is no longer needed, to avoid memory leaks
If the function is processing an array in the form of a pointer, it needs to be aware of the size of the array to avoid undefined behavior, typically as an extra size parameter or a global constant
A pointer is like a shortcut or a hyperlink. Creating just a shortcut does not install a program. Creating a hyperlink does not magically sets up the whole website.
Same with a pointer: a int* is a pointer to an integer. It is not the integer itself. As such you must make sure that the pointer points to something meaningful before you try to follow the pointer.
One way of doing so is to create an integer and the sets a pointer to point to it:
int* ret_val = new int;
This will create an integer (the new operator), and then sets the ret_val pointer to point to it.
Objects created through new exist until you explicitly destroy them through delete or when your application ends. For that reason, if you have new int in a function, it is safe to access it even if the function ends.
What would be dangereous, and probably caused your concern, is if you would set the pointer ret_val not to a new integer, but to an existing local variable, i.e.
int myInteger;
int* ret_val = &myInteger;
In such scenario, ret_val points to a local variable myInteger which gets destroyed when the scope containing the declaration ends. You end up with a dangling pointer, referencing stuff that does not exist (think: broken hyperlink). Using such a pointer can lead to undefined behavior. It may crash your program, but it may as well silently accept it, modifying some random space in memory.
So, a function of the shape:
int* foo(void)
{
int* ret_val = new int;
*ret_val = 1234;
return ret_val;
}
is safe to use. It is not necessarily a good practice: the user of such function must know that it creates a new integer, that later - at some point - someone should delete. Functions that do that typically highlight such behavior in some way, e.g. through its name. For example, allocateInt() makes it clear that it created something that later should be delete. In contrast, getInt() suggests that the integer already exists and nothing new is created.
You should consider:
int *foo() {
int *ret_val = new int(1234);
return ret_val;
}
instead of (bad code):
int* foo(void)
{
int * ret_val;
*ret_val = 1234;
return ret_val; // dangling pointer!
}
otherwise you will have dangling pointer (the second example).
Obviously don't forget to release the memory.
You should also consider using smart pointers:
https://en.wikipedia.org/wiki/Smart_pointer
As you specified both C++ and C languages the above code is in C++ (operator new), please refer to (e.g.) #Mattia F. answer for ANSI C.

Is there a one line approach to declaring and initializing pointer variables?

When I need to create a pointer variable, I currently use the following approach which works:
int getIntPointer()
{
int * intPointer = new int;
*intPointer = 0;
return *intPointer;
}
likewise, when returning such a pointer from another function I would use something like this in main() to use it:
int main()
{
int * intPointer = new int;
*intPointer = getIntPointer();
delete intPointer;
}
This all works, but for readability and efficiency I'd like to know is if there are one line equivalents. (and I don't mean to just put them on the same line. I mean a short hand approach.)
Also: In this above example, I used the same pointer variable in both functions, and it works. Are they the same pointer in memory? Adding something like:
delete intPointer;
Immediately after the return statement doesn't crash the program, but does it even get there? Or is it safe to just delete it's passed iteration in main when no longer needed?
You could do:
int *intPointer = new int(0);
(or new int(100); if you want intPointer to point at the value 100).
And of course, you could shorten that to :
return new int(0);
assuming you don't need to do anything else with the pointer.
Note that:
int * intPointer = new int;
*intPointer = getIntPointer();
is incorrect. Either you mean:
int * intPointer = new int;
intPointer = getIntPointer();
in which case it's a memory leak, because you are overwriting intPointer from new with the one created by the call.
Or you mean to write:
int * intPointer = new int;
*intPointer = *getIntPointer();
in which case there is a memory leak because getIntPointer called new and you "lost" that pointer by not saving the return value.
For EVERY new you call, you should have exactly one corresponding delete, or it is a memory leak. Since both of my examples above does NOT provide that, because both cases will lose one of the pointers returned from new, this is incorrect.
In general, it is best to NOT use "raw pointers", and instead use either std::unique_ptr (if you only ever expect the pointer to "live" in one place at a time) or std::shared_ptr (if you expect multiple objects to have a copy of the pointer).
Edit: My answer above assumes that getIntPointer actually does what the name describes, rather than what the code in the question does, which is rather poor design: allocate memory and then return the pointed-to value.
I could be wrong, but I think you're reaching for std::shared_ptr and its helper function std::make_shared.
std::shared_ptr< int > intPointer = std::make_shared< int >( 42 );
Rather than repeat all the use cases of smart pointers here, I'll simply link to an answer that goes into more detail on the topic.
inb4 rants about why smart pointers are good or bad.

Assign value to deleted object

I have a small homework problem.
The following code is given:
int * p;
p = new int;
*p = 5;
The question is: Why is it useless to do
p = 0;
delete p;
but usefull to do
delete p;
p = 0;
?
In my opinion, both is useless. If an object is deleted, no new value can be assigned.
I also get in both cases a Segmentation fault.
For Why it is useful for the following:
delete p;
p = 0;
Quoting from stroustrup's answer: Why doesn't delete zero out its operand?
Consider
delete p;
// ...
delete p;
If the ... part doesn't touch p then the second "delete p;" is a serious error that a C++ implementation cannot effectively protect itself against (without unusual precautions). Since deleting a zero pointer is harmless by definition, a simple solution would be for "delete p;" to do a "p=0;" after it has done whatever else is required.However, C++ doesn't guarantee that.
One reason is that the operand of delete need not be an lvalue. Consider:
delete p+1;
delete f(x);
Here, the implementation of delete does not have a pointer to which it can assign zero. These examples may be rare, but they do imply that it is not possible to guarantee that any pointer to a deleted object is 0.'' A simpler way of bypassing thatrule'' is to have two pointers to an object:
T* p = new T;
T* q = p;
delete p;
delete q; // ouch!
C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.
If you consider zeroing out pointers important, consider using a destroy function:
template<class T> inline void destroy(T*& p) { delete p; p = 0; }
Consider this yet-another reason to minimize explicit use of new and delete by relying on standard library containers, handles, etc.
Note that passing the pointer as a reference (to allow the pointer to be zero'd out) has the added benefit of preventing destroy() from being called for an rvalue:
int* f();
int* p;
// ...
destroy(f()); // error: trying to pass an rvalue by non-const reference
destroy(p+1); // error: trying to pass an rvalue by non-const reference
Recall that deleting 0 is allowed. Therefore, when you do this
p = 0;
delete p; // Deleting zero is ignored
you throw away the old value of p (thus creating a memory leak), and then call delete 0, which is ignored.
When you do this, however
delete p;
p = 0;
you use the old value first (to de-allocate the int), and only then zero it out. This makes sense, because the old value of p becomes both useless and dangerous as soon as delete is executed.
This sets the pointer to null and then calls delete:
p = 0;
delete p;
It is like saying
delete 0;
I think what you are thinking is that it is setting the int that p points to to zero, but that would be done like this:
*p = 0;
p = NULL;
and
p = 0;
In the above case you are assigning value to the pointer and not to the object it points to.
Are one and the same. delete function is used to free the memory allocated dynamically to an object.
When you say
delete p;
p = 0;
It is like saying free the memory allocated to the pointer p and
then you are saying assign the pointer to NULL. Which is right.
In the other case when you do this
p = 0;
delete p;
You are saying assign the pointer to NULL first. Now the pointer p
is not pointing to any valid dynamically assigned memory. So later
when you say delete p the compiler cannot find any memory to free
and hence throws a segmentation fault.
In the first case, you are assigning the value of the POINTER p to be '0', not the value of the int that p points to. That's why it is both useless (will in fact cause a memory leak), and causes a seg fault when you try to delete from memory address '0'. EDIT - actually I just learned that the segfault is not caused by the 'delete 0', which is ignored according to the standard, so something else is causing that.
In the second case you are freeing the memory / object pointed to by p (which should be fine), and then assigning the pointer to have a value '0', which should also be Ok, so not sure why you are seg faulting there? In terms of usefulness, it used to be considered good practice to set free'd pointers to a null or '0' value so you can test for that before de-referencing them.

Return pointer to data declared in function

I know this won’t work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4;
return &x;
}
So how do I correctly return a pointer to something I create within the function, and what do I have to take care with? How do I avoid memory leaks?
I've also used malloc:
int* myFunction2()
{
int* x = (int*)malloc(sizeof int); *x = 4; return x;
}
How do you correctly do this - in C and C++?
For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr or boost::shared_ptr are good options.
Your second approach is correct. You just need to clearly document that the caller "owns" the result pointer, and is responsible for freeing it.
Because of this extra complexity, it is rare to do this for "small" types like int, though I'm assuming you just used an int here for the sake of an example.
Some people will also prefer to take a pointer to an already allocated object as a parameter, rather than allocating the object internally. This makes it clearer that the caller is responsible for deallocating the object (since they allocated it in the first place), but makes the call site a bit more verbose, so it's a trade-off.
For C++, in many cases, just return by value. Even in cases of larger objects, RVO will frequently avoid unnecessary copying.
One possibility is passing the function a pointer:
void computeFoo(int *dest) {
*dest = 4;
}
This is nice because you can use such a function with an automatic variable:
int foo;
computeFoo(&foo);
With this approach you also keep the memory management in the same part of the code, ie. you can’t miss a malloc just because it happens somewhere inside a function:
// Compare this:
int *foo = malloc(…);
computeFoo(foo);
free(foo);
// With the following:
int *foo = computeFoo();
free(foo);
In the second case it’s easier to forget the free as you don’t see the malloc. This is often at least partially solved by convention, eg: “If a function name starts with XY, it means that you own the data it returns.”
An interesting corner case of returning pointer to “function” variable is declaring the variable static:
int* computeFoo() {
static int foo = 4;
return &foo;
}
Of course this is evil for normal programming, but it might come handy some day.
C++ approach to avoid memory leaks. (at least when You ignore function output)
std::auto_ptr<int> myFunction() {
std::auto_ptr<int> result(new int(4));
return result;
}
Then call it:
std::auto_ptr<int> myFunctionResult = myFunction();
EDIT: As pointed out by Joel. std::auto_ptr has it's own drawbacks and generally should be avoided.
Instead std::auto_ptr You could use boost::shared_ptr (std::tr1::shared_ptr).
boost::shared_ptr<int> myFunction() {
boost::shared_ptr<int> result(new int(5));
return result;
}
or when use C++0x conforming compiler You can use std::unique_ptr.
std::tr1::unique_ptr<int> myFunction() {
std::tr1::unique_ptr<int> result(new int(5));
return result;
}
The main difference is that:
shared_ptr allows multiple instances of shared_ptr pointing to the same RAW pointer. It uses reference counting mechanism to ensure that memory will not be freed as long as at least one instance of shared_ptr exist.
unique_ptr allows only one instance of it holding pointer but have true move semantic unlike auto_ptr.
In C++, you should use new:
int *myFunction()
{
int blah = 4;
return new int(blah);
}
And to get rid of it, use delete:
int main(void)
{
int *myInt = myFunction();
// do stuff
delete myInt;
}
Note that I'm invoking the copy constructor for int while using new, so that the value "4" is copied onto the heap memory. The only way to get a pointer to something on the stack reliably is to copy it onto the heap by invoking new properly.
EDIT: As noted in another answer, you will also need to document that the pointer needs to be freed by the caller later on. Otherwise you might have a memory leak.
There is another approach - declare x static. In this case it will be located in data segment, not on stack, therefore it is available (and persistent) during the program runtime.
int *myFunction(void)
{
static int x = 4;
return &x;
}
Please note that assignment x=4 will be performed only on first call of myFunction:
int *foo = myFunction(); // foo is 4
*foo = 10; // foo is 10
*foo = myFunction(); // foo is 10
NB! Using function-scope static variables isn't tread-safe technique.
Your second code snippet is correct.
To help avoid memory leaks, I let the coding conventions help me.
xxxCreate() will allocate memory for xxx and initialize it.
xxxDelete() will destroy/corrupt xxx and free it.
xxxInit() will initialize xxx (never allocate)
xxxDestroy() will destroy/corrupt xxx (never free)
Additionally, I try to add the code to delete/destroy/free as soon as I add the code to create/init/malloc. It's not perfect, but I find that it helps me differentiate between items that need to be freed and those that don't, as well as reducing the likelihood that I will forget to free something at a later time.
Boost or TR1 shared pointers are generally the way to go. It avoids the copy overhead, and gives you semi-automatic deletion. So your function should look like:
boost::shared_ptr<int> myFunction2()
{
boost::shared_ptr<int> x = new int;
*x = 4;
return x;
}
The other option is just to allow a copy. That's not too bad if the object is small (like this one) or you can arrange to create the object in the return statement. The compiler will usually optimize a copy away if the object is created in the return statement.
I would try something like this:
int myFunction2b( int * px )
{
if( px )
{
*px = 4;
return 1;
}
// Choice 1: Assert or Report Error
// Choice 2: Allocate memory for x. Caller has to be written accordingly.
// My choice is 1
assert( 0 && "Argument is NULL pointer" );
return 0;
}
You're asking how to correctly return a pointer. That's the wrong question, because what you should be doing is using smart pointers rather than raw pointers. scoped_ptr and shared_ptr (available in boost and tr1) are good pointers to look at (e.g. here and here)
If you need the raw pointer for something (e.g. passing to a C function), the get() method will supply it.
If you must create raw pointers, e.g. for homework, then you can use malloc() (as you did) or new within a function, and hope you remember to de-allocate the memory (through free() and delete respectively) Or, in a slightly-less-likely-to-leak idiom, you can create the pointer with new, pass it to a function, and de-allocate with delete when you're done with it. Again, though, use smart pointers.