From https://cs50.stackexchange.com/questions/4671/memory-allocation-recommended-practices I read "you don't have to declare all your pointers, allocate memory for them and/or free the allocated memory in main". But I, unsuccessfully (execution returns Segmentation fault: 11
), tried:
#include <stdio.h>
#include <stdlib.h>
void gener_random(int size, int *values) {
values = malloc(size * sizeof(values));
for(int i = 0; i < size; i++)
values[i] = rand();
}
int main(int argc, char **argv) {
int size = 10;
int *values;
gener_random(size, values);
for(long i = 0; i < size; i++)
printf(" %d", values[i]);
return 0;
}
Instead, moving malloc
inside main
works:
void gener_random(int size, int *values) {
for(int i = 0; i < size; i++)
values[i] = rand();
}
int main(int argc, char **argv) {
int size = 10;
int *values;
values = malloc(size * sizeof(values));
gener_random(size, values);
for(long i = 0; i < size; i++)
printf(" %d", values[i]);
return 0;
}
What's going on?