0

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?

3
  • just as a bit of information: do not declare variable instances in a header file. Rather, declare the global variable outside of any function in one of the .c files, then declare the same variable in a header file, prefixed with extern. Any files that use that global variable can access it by #include the header file and then using the variable as if it were local to the current .c file. Commented Oct 12, 2015 at 22:59
  • The pointer 'p' is not pointing to any specific user memory. in global memory, which the process initializes to 0x00, Accessing address 0, which is not part of the user accessible memory is what is causing the seg fault event. Commented Oct 12, 2015 at 23:04
  • Doesn't *p mean that the value that p is pointing to is equal to 5? Commented Oct 12, 2015 at 23:07

2 Answers 2

1

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) );
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that as well, but still doesn't print the digit
Oh actually, my console scrolled up. It worked. Thanks
1

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);
}

2 Comments

Ok,so I added this line, but it still doesn't print the digit
Oh actually, my console scrolled up. It worked. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.