0

I want to write a program that alloc a dynamic array in memory and have it keep listening for input until the value "-1". I've do this, but it uses too much memory.

int *a=malloc(sizeof(int));
int i=0;
int j;
while (a[i-1]!=-1){
scanf("%d",a+i);
i++;
a=realloc(a,(i+2)*sizeof(int));
                   }
7
  • 3
    Please define "too much memory". And what value do you expect a[i-1] to be when i is 0? Commented Dec 5, 2016 at 3:11
  • ok, and how can i do it in alternative? Commented Dec 5, 2016 at 3:13
  • Do what? To fix the a[i-1] problem you can change the loop from while to do/while. Commented Dec 5, 2016 at 3:15
  • nono, i don't want use the string, i want use the number Commented Dec 5, 2016 at 3:17
  • i need a alternative way to do a dynamic array using a terminal value in iput Commented Dec 5, 2016 at 3:19

1 Answer 1

1

You are not handling input error. If scanf fails to read, your program has undefined behaviour which may result in it quickly eating up all your memory and then crashing.

It's also advised to handle realloc failure, and also not reallocate every single time around.

Putting this all together, and also avoiding adding -1 to the array, it might look something like this:

/* values are read into this buffer */
int size = 16, count = 0;
int *a = malloc(size * sizeof(int));

/* loop control variables */
int done = 0;
int error = 0;

/* temporary variables */
int val, new_size, *new_a;

while( !done )
{
    /* double the buffer size when required */
    if( count == size )
    {
        new_size = size * 2;
        new_a = realloc(a, new_size * sizeof(*a));
        if( !new_a ) {
            perror("Realloc failed");
            error = 1;
            break;
        } else {
            a = new_a;
            size = new_size;
        }
    }

    /* read value and finish on input error or if user enters -1 */
    if( 1 != scanf("%d", &val) || val == -1 ) {
        done = 1;
    } else {
        a[count++] = val;
    }
}
Sign up to request clarification or add additional context in comments.

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.