Pass and pass-by-value in C ++

In the transfer pointer, but also problems related to the pass-pass value. The following will be described by a function.

code show as below:

bool openBinary(uchar* buffer)
{
    long lSize = 1024;
    buffer = (uchar*)malloc(sizeof(uchar)*lSize);
    return true;
}
int main(int agrc, char *agrv[]){
  uchar *buffer_0 = NULL;
  openBinary(buffer_0);
  return 0;
}

After the above code, executed openBinary function, buffer_0 remains a null pointer.

The reason is because, when executed openBinary function, the function generates a value of the same buffer_0 uchar * temporary variables buffer, before allocating memory temporary variable buffer and values ​​buffer_0 same, but after allocating memory dynamically allocated memory address assigned to a temporary variable buffer. From this moment, the value of the temporary variable buffer and buffer_0 is not the same, buffer_0 still a null pointer, and a temporary variable buffer points to the first address of the newly allocated memory. After openBinary function is finished, the temporary variable buffer is destroyed, it becomes a passing buffer_0, and the buffer was pointing to the memory I do not know, last buffer_0 nothing.

If you like to make buffer_0 end up memory when you need to pass the function call site rather than by value.

code show as below:

bool openBinary(uchar* &buffer)
{
    long lSize = 1024;
    buffer = (uchar*)malloc(sizeof(uchar)*lSize);
    return true;
}
int main(int agrc, char *agrv[]){
  uchar *buffer_0 = NULL;
  openBinary(buffer_0);
  return 0;
}

The code above, openBinary function references buffer_0 passed in dynamically allocated memory of, buffer_0 is involved in real, after the function executes, buffer_0 was available memory.

Finally, note that after the completion of the memory usage to be released.

 

Guess you like

Origin www.cnblogs.com/Peyton-Li/p/11023029.html