Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value by pointer error

Tags:

c++

pointers

I don't understand why is crashing. I send a pointer to an array, alloc that array and then modify array. What is the problem?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void f(unsigned char *data) {
    data = (unsigned char *)malloc(200);
}

int main() {
    unsigned char *data = nullptr;
    int i;
    f(data);
    memset(data, 0, 200);
}
like image 276
MSD561 Avatar asked Jan 24 '26 17:01

MSD561


1 Answers

You are passing data by value to f().

f() sets the value of its parameter.

Because the parameter was passed by value, this does absolutely nothing to the data variable in main(). f() leaks the allocated memory, and when it returns, main()'s data is still nullptr.

You should pass it by reference:

void f(unsigned char *&data)

Or, better yet, return it. f() doesn't need the parameter.

unsigned char *f() {
    return (unsigned char *)malloc(200);
}
like image 96
Sam Varshavchik Avatar answered Jan 26 '26 09:01

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!