0

I am new to C and I was trying to programm a dynamic int Array which gets its values via terminal. I got it to work but it only works for a few numbers before i get the following error: realloc(): invalid next size Aborted. I would like to know why that is Here is my code so far:

void dynamicIntArray(){
    int *dynamicArray = malloc(0);
    int length = 0;

    printf("Please put in your numbers: \n");
    while(1){
        int x;
        scanf("%d", &x);

        if(x == -1){ break; }
        else{
            dynamicArray = realloc(dynamicArray, sizeof(int));
            if(dynamicArray == NULL){ return EXIT_FAILURE; }
            dynamicArray[length++] = x;
        }
    }
}


int main(){
    dynamicIntArray();
    return 0;
}

3
  • The second argument of realloc is the new size of the array in bytes Commented May 9, 2021 at 21:11
  • Oh ok thanks I thought it expends by this value ok makes sense. Commented May 9, 2021 at 21:18
  • You did not check the return value of scanf(), meaning any use of x after that line may invoke undefined behavior. Commented May 9, 2021 at 22:16

2 Answers 2

2

Replace

realloc(dynamicArray, sizeof(int))

With

realloc(dynamicArray, length * sizeof(int))

The former option will allocate memory for a single int. Accessing element at index other than zero invokes undefined behaviour, likely a crash.

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

Comments

0

This is my solution now. I also had to change the index when assigning a new value to dynamicArray otherwise it would always hold the default int value at index 0 which makes me think malloc(0) is exactly the same as malloc(1).

void dynamicIntArray() {
    int *dynamicArray = malloc(0);
    int length = 0;

    printf("Please put in your numbers: \n");

    while(1) {
        int x;
        scanf("%d", &x);

        if(x == -1) { break; }
        else {
            dynamicArray = realloc(dynamicArray, ++length*sizeof(int));

            if(dynamicArray == NULL) { return EXIT_FAILURE; }

            dynamicArray[length-1] = x;
        }
    }
}

int main() {
    dynamicIntArray();
    return 0;
}

1 Comment

Please don't answer your question with a "here is my solution now" response. It's not really a clear answer. Think about how others who come to the site are seeing a similar problem and want to know where it is failing. tstanisl's answer points you to the right place.

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.