segmentation fault for extern

Why this is happening when both of them compiled together and run?

I am getting segmentation fault SIGSEGV.

File1.c:

int arr[80];

File2.c:

extern int *arr;
int main() {
   arr[1] = 100;
}

You need to remember that pointers and arrays are not the same, no matter what anybody tells you. (There are some conveniences provided where you can treat an array as a pointer (and vice versa), but they hide what's really going on.) Your declaration as a pointer with "extern int arr" makes the sizeof(void) bytes at location "arr" get treated as if they point to something, when in fact they contain garbage since you've defined an array there, not a pointer. The first few bytes of the array (i.e. the garbage) are dereferenced as if they were a pointer, and a segfault is the likely result.

Solution: Make both the declaration and the definition the same. Additionally, put the declaration in a header and make sure that File1.c #includes it, and that will prevent this sort of thing from happening.

More specifically: A pointer is an integer variable that holds a memory address. It takes a small and fixed number of bytes. You're using it to point to memory stored elsewhere.

When you define it as an array, you're telling it that all the memory for that array is stored at the memory address of the pointer, not the memory address stored in the pointer. It expects 80 bytes of data right there, not where it points to.

You could do "extern int arr[]" perhaps. That way you're telling it it's an array, as you'd expect, but the size at least wouldn't have to be known.

More precisely:

  1. A pointer is an L-value (a variable in memory that you can assign a result to) that points to an address in memory.

  2. An array is an area of memory. The "naked" name of an array is interpreted as the address of the zeroth element of the array. The "naked" name of an array is not an L-value and you can't assign anything to it. Trying to do so is a syntax error.

Thus you can substitute the naked name of an array when a pointer of the same type is expected.