Reputation: 1633
I get a segmentation fault when trying to run the code below
#include <stdio.h>
int main(){
int* tes1;
int* tes2;
*tes1=55;
*tes2=88;
printf("int1 %p int2 %p \n",tes1,tes2);
return 0;
}
why is that?
Upvotes: 0
Views: 71
Reputation: 14323
You need to allocate the pointers, otherwise they point to garbage memory:
int* tes1; //random initial value
int* tes2; //random initial value
In order to make them point to assignable memory, use the malloc
function:
int* tes1 = malloc(sizeof(int)); //amount of memory to allocate (in bytes)
int* tes2 = malloc(sizeof(int));
Then you safely use the pointers:
*tes1=55;
*tes2=88;
But when you're done, you should free the memory using the free
function:
free(tes1);
free(tes2);
This will release the memory back to the system and prevent a memory leak.
Upvotes: 3
Reputation: 99670
You are declaring pointers, and then trying to define values of pointer of the pointers
#include <stdio.h>
int main(){
int* tes1;
int* tes2;
tes1=55; //remove the * here
tes2=88;
printf("int1 %p int2 %p \n",tes1,tes2);
return 0;
}
Upvotes: 1