MSD561
MSD561

Reputation: 512

Pass value by pointer error

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);
}

Upvotes: 2

Views: 90

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Change

 void f(unsigned char *data) { // ....

to

 void f(unsigned char *&data) { // ....
                    // ^
 }

or

 void f(unsigned char **data) {
     *data = (unsigned char *)malloc(200);
 }

and call

 f(&data);
// ^

It's all about passing a reference to the data pointer to be initialized from within the function.

Your example passes data by value, and doesn't change the pointer outside of the function.

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118310

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);
}

Upvotes: 6

Scott Hunter
Scott Hunter

Reputation: 49803

The call to f does not change the value of the variable data defined in main, as you seem to expect it to. It changes the value of the data defined in f, but because parameters are passed by value, that has no effect on the data defined in main.

Upvotes: 3

Related Questions