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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With