0

So I have this code

int *userInput; //array place holder
//int max; //Max variable for later use in comparisons
int start = 0; //inital starting point value for loops
int endUserInput; //used to find the total number input




printf("You may enter up to a max of 50 integer values, Please enter the first value: ");

//loop collects the user inputs
/* Using a while loop to check for data to be true in what is entered
 to spot when the data becomes false when a letter is entered*/
while (scanf("%d", &userInput[start]) == 1) {
    //If statement entered to catch when the total is met
    if (start == 49) {
        break;
    }
    start = start + 1;
    //Print statement to let user know what value they are at and how to end input
    printf("Enter next value %d or enter C to calculate: ", start + 1);

}

It runs on my MBP compiler but on Dev on a PC it crashes with memory error? the error being int *userInput declaration. What can I do to fix this without assigning specifics to the array.

2
  • 1
    You have to allocate memory for userInput. Commented Feb 28, 2014 at 1:44
  • Could you give us a more detailed look at the error message please? Commented Feb 28, 2014 at 1:57

2 Answers 2

2

You're overwriting unallocated memory, which might include very important things. You need to allocate enough room to store 50 integers and set userInput to that value.

int *userInput = malloc(sizeof(*userInput)*50);

Don't forget to call free(userInput) when you've finished using it.

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

1 Comment

Don't cast the result of malloc. int *userInput = malloc(50 * sizeof(*userInput)); is more robust.
0

Replace

int *userInput;

with

int userInput[50];

and your code will work.

The problem is that you've created a pointer to an array, but you never created any memory for it to point to. The above solution ensures there is space for 50 integers on the stack, and points userInput to it. That way, when you access the memory pointed to by userInput, there is valid memory ready to be used. Your existing code has no such memory so your computer will try to write to whatever the pointer points to, which could be anything (the middle of nowhere, some of your code, other data in the program, etc) as it wasn't initialized.

Comments

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.