c - void pointer as an argument in function -


this question has answer here:

i have function f1 expects void pointer. caller want have generic logic of passing void pointer a modifies pointer internally.

sample code pasted below :

#include "stdio.h" #include "malloc.h" void f1(void* a) {     printf("f(a) address = %p \n",a);     = (void*)(int*)malloc(sizeof(int));      printf("a address = %p \n",a);     *(int*)a = 3;      printf("data = %d\n",*(int*)a); }  void f(void) {     void* a1=null;     printf("a1 address = %p \n",a1);      f1(a1);      printf("a1 address = %p \n",a1);     printf("data.a1 = %d\n",*(int*)a1); }  int main() {     f(); } 

but causes segmentation fault. there way make work without changing prototype of function f1?

c uses pass-by-value function argument passing. if have change passed variable inside function, need have pointer variable.

in case, should pointer pointer.

otherwise, after call f1(a1);, in f(), a still null , dereferencing invokes undefined behaviour. segmentation fault 1 of side effects of ub.

that said,

  1. please see why not cast return value of malloc() , family in c.

  2. you don't need #include "malloc.h" use malloc(), rather use #include <stdlib.h>. declared in stdlib.h header file.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -