0

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

2
  • Do you use more than one thread? Commented Feb 5, 2017 at 7:37
  • No, at least not intentionally. Although Rajesh posted the solution below, I wonder about that Thread 2 part. Perhaps main() gets its own thread? Commented Feb 5, 2017 at 8:12

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you. I had moved the intArray declaration into global space for the express purpose of using printArray() and forgot to remove the declaration portion inside main()

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.