I have written a code in C in which I have defined a function which takes void* as its argument and also returns void*. I am getting few warnings and Segmentation Fault
during execution.
Please let me know if I am doing something silly. I am somewhat new to all these.
Code:
#include <stdio.h>
#include <stdlib.h>
void *fun1(void *a) {
int temp = *((int*)a); // Typecasting the received void* valud dereferencing it.
temp++;
return ((void*)temp); // Returing the value after typecasting.
}
int main()
{
printf("Hello World\n");
int a =5;
int *p = &a;
int b = *p;
printf("%d %d",a,b);
int x = *((int*)fun1((void*)&b)); /*
Here I am trying to send "b" to "fun1" function after doing a typecast.
Once a value is receievd from "fun1" , I am typecasting it to int*.
Then I am deferencing the whole thing to get the value in int format.
*/
printf("\n%d",x);
return 0;
}
O/P:
main.c:8:13: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
Hello World
Segmentation fault (core dumped)
From GDB debugger, I found that the segmentation fault is occurring at the line 20 after the value is returned from fun1()
. I suspect that the way I am sending the value b to fun1()
is wrong.
Also, why the intermediate printf
statement in line 18 printf("%d %d",a,b);
isn't executing?