Zed Zed - 4 years ago 161
C Question

Segmentation Fault when accessing global integer array

I am writing C code to take user parameters and build an integer array from them. I ask the user to provide the array length and each element's value.

Running the following code causes an error at the

printArray()
function call. Following the debugger into printArray(), the Segmentation Fault itself occurs at
printf("%d", intArray[i])


NOTE: The array is correctly printed when I copy the
printArray()
code into
main()
instead of making a function call. This makes me think that I have an issue with global variables and/or pointers. I am still learning C, so your guidance is appreciated.

How can I fix this? See debugger output at the bottom for more info.

void printArray();

int arraySize;
int* intArray;

int main() {

printf("Enter array length:\n");

scanf("%d", &arraySize);
int* intArray = (int*) malloc(sizeof(int)*arraySize);

printf("Enter an integer value for each array element:\n");
for (int i = 0; i < arraySize; i++) {
printf("Enter element %d:\n", i);
scanf("%d", &intArray[i]);
}

printArray();
return 0;
}

void printArray() {
printf("[");

for (int i = 0; i < arraySize; i++) {
printf("%d", intArray[i]);
}
printf("]\n");
}


debugger output

Answer Source

I think you have redeclared intArray variable in main()

int* intArray = (int*) malloc(sizeof(int)*arraySize);

by doing this, the scope of this variable is only in the main function and printArray() does not know about this definition. So printArray() tries to access intArray variable which you have declared globally(which does not have definition) and thus leading to segmentation fault.

So just give intArray = (int*) malloc(sizeof(int)*arraySize);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download