Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a heap-allocated pointer from function OK?

Tags:

c++

c

pointers

When we return from function, if return value is a pointer, it must be define as static. Is this true for heap memory allocated pointer (such as new/malloc pointers),too?

consider this example:

#include"stdio.h"
char * func()
{
    char * X=new char[10];
    X[0]='C';
    x[1]='\0';
    return X;//is it a good return from function?
}
main()
{
    char * A=func();
    puts(A);
    delete[] A;
}
like image 650
MD128 Avatar asked Jun 10 '15 11:06

MD128


2 Answers

As others already pointed out, technically, the code is okay.
However, the real problem with the code is the function signature char * func(). It only specifies that it will return a pointer to a char. That pointer can be

  • a normal pointer to a char variable
  • a pointer to a char array
  • a pointer to a c-style string

The pointer can point to

  • static memory
  • heap-allocated memory that will be freed somewhere else
  • heap-allocated memory that you are suppose to free yourself.

There is no way of knowing what to do unless you want to trust the documentation or to investigate in possibly a lot of code (functions calling functions calling functions...).

This can be avoided by returning

  • a char
  • an std::string
  • a container
  • a smart pointer.

Manual memory management is hard to get right within a complete application and should never be your main concern, so it should be avoided and not hidden by functions returning pointers.

like image 188
stefaanv Avatar answered Sep 27 '22 21:09

stefaanv


Besides the weird increment/decrement fiddling, the code is okay.

The variable X goes out of scope when the function returns, but that's only the actual variable and not what it points to.

Pointers are basically simple integers, whose contents just happens to be an address to somewhere in memory, and treated specially by the compiler. What happens when the function returns is that the contents of the variable X is copied before the variable goes out of scope. Then the copy of the contents (the actual memory address) is again copied, this time to the variable A in the calling function.

like image 26
Some programmer dude Avatar answered Sep 27 '22 23:09

Some programmer dude