Reputation: 199
So I have created couple of files:
file1.c
#include "file2.h"
...
int *p; <-GLOBAL VARIABLE
...
void main(){
printer();
}
file2.c
#include "file1.h"
void printer(){
*p = 5;
printf("%d",*p);
}
file1.h
extern int *p;
file2.h
extern void printer(void);
Code compiles. However, when I run it, I get segmentation error. I have tried to look for the solution everywhere, but couldn't find a good one.
I tried replacing printer(void)
in file2.h with printer()
no result (and not sure if it is correct, either).
Does anyone possibly see a solution to my issue?
Upvotes: 0
Views: 33
Reputation: 4681
Think of this in terms of one file:
#include <stdio.h>
int *p; <-GLOBAL VARIABLE
void printer();
void main(){
printer();
}
void printer(){
*p = 5;
printf("%d",*p);
}
What you've done is taken an initialized but undefined variable of a pointer that points to an integer. When you go to set that pointer, it is not initialized. You need to either initialize it and reference it with &, or better yet, allocate memory for it dynamically.
Perhaps in your main function, you can do something like:
int main(){
p = calloc(1, sizeof(int));
printer();
free(p);
}
Upvotes: 1
Reputation: 48121
You've never allocated memory for p
to reference, or otherwise initialized it as a reference to properly-allocated memory. When you do *p = 5
, you are trying to reference memory you aren't allowed access to.
A typical solution would be to dynamically allocate memory, e.g.:
p = malloc( sizeof(int) );
Upvotes: 1