The value of p in main hasn't been changed after calling the function reallocmem, so a segmentation fault happened because the program tries to dereference the NULL pointer.
To pass a pointer as an argument and change it, we need to pass a pointer of the pointer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int reallocmem(int **p, size_t newsize) {
void *q;
q = realloc(*p, newsize);
if (q != NULL) {
*p = q;
return 1;
}
return 0;
}
int main(void) {
int *p = 0x0;
if (!reallocmem(&p, 10 * sizeof(int))) {
fprintf(stderr, "Could not reallocate memory\n");
free(p);
return 0;
}
int i;
int size = 10;
for (i = 0; i < size; i++) {
p[i] = i * 2;
}
for (i = 0; i < size; i++) {
printf("%d\n", p[i]);
}
free(p);
}
Online demo
The C program passes every argument by value, if you add printf statement in your code, you will find that the p in reallocmem have a different address with the p in main, so in order to change the p in main, we need to pass the address of p(pointer to pointer) but not the value of p. Or the local copy of p in reallocmem has been changed, but it won't affect the caller function main.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int reallocmem(int *p, size_t newsize) {
printf("%p\n", &p);
void *q;
q = realloc(p, newsize);
if (q != NULL) {
p = q;
return 1;
}
return 0;
}
int main(void) {
int *p = 0x0;
printf("%p\n", &p);
if (!reallocmem(p, 10 * sizeof(int))) {
fprintf(stderr, "Could not reallocate memory\n");
}
int i;
int size = 10;
for (i = 0; i < size; i++) {
p[i] = i * 2;
}
for (i = 0; i < size; i++) {
printf("%d\n", p[i]);
}
free(p);
}
pdoes not reflect after thereallocmem()call. you need to pass a double pointerif(!reallocmem(p,10*sizeof(int))){ fprintf(stderr,"Could not reallocate memory\n"); }do not continue to exec the program if the function:reallocmem()failsint *p = 0x0; if(!reallocmem(p,10*sizeof(int))){to change the contents of a pointer, need t pass the address of the pointer, similar to:int *p = 0x0; if(!reallocmem(&p,10*sizeof(int))){and the function:reallocmem()needs to be modified to access through that parameter to the original pointer