c - void pointer as an argument in function -
this question has answer here:
- c actions , variables 1 answer
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,
please see why not cast return value of
malloc()
, family inc
.you don't need
#include "malloc.h"
usemalloc()
, rather use#include <stdlib.h>
. declared instdlib.h
header file.
Comments
Post a Comment