0

When input is '1 2 3 4 5 6 7 8 9 10 11' Expected output should be the same as input. Yet the output is '1 2 3 4 5 6 7 8 9 10 -1850774484' . Only happens when there are more than 10 integers being inputted. Where did I go wrong with my realloc line

#include <stdio.h>
#include <stdlib.h>

#define INITIAL_SIZE 10

int
main(int argc, char **argv){
    int i = 0, num, size = 0, n = INITIAL_SIZE;
    int *A;

    A = malloc(n * sizeof(int));

    if(A == NULL){
        printf("OUT OF MEMORY\n");
        exit(EXIT_FAILURE);
    }

    while(scanf("%d",&num) == 1 && getchar()!='\n'){
        A[i] = num;
        i++;
        size++;
        if (size >= n){
            n = n * 2;
            A = realloc(A,n * sizeof(int));
        }
    }

    printf("Int Array: ");
    for (i = 0; i <= size; i++){
        printf("%d ", A[i]);
    }
    printf("\n");

    return 0;
}

1 Answer 1

5

There is nothing wrong with the realloc. You are printing an extra uninitialized index in the last loop. Fix it by changing

for (i = 0; i <= size; i++)

to

for (i = 0; i < size; i++)

The only problem with the realloc is that you don't check if it was successful just like you did for the malloc. Another problem is that you don't free the allocated memory.

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

12 Comments

yep my input is '1 2 3 4 5 6 7 8 9 10 11\n' and output gives '1 2 3 4 5 6 7 8 9 10' . it seems if i remove the 'getchar()...' part and end by using control-D instead gives me the correct output though
@Qbb , Use BLUEPIXY's solution instead or add A[i]=num; size++; i++; after the while loop.
@MOehm Read i as next index and size as current size! When we pass A[i] = num; with i == 9 both i and size are incremented to 10 and the realloc is triggered because it uses size >= n (or equal to). So I think the loop is fine - except it could perform an unnecessarily reallocation which is why we would normally reallocate before assignment. However this code is valid.
@DanAllen: Yes, you're right. i is accessed before it is incremented. I got that wrong, because I usually enlarge the space just before I need it, not after it. Sorry for that.
@Qbb , I'm getting too confused. Here is the solution which uses BLUEPIXY's method. Note that I've not freed or checked the return value of realloc in the code.
|

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.