0

I'm writing a program that need to scan numbers into an array, and I know that the number of items on my array will be a multiple of 5. I can't use the realloc function, only malloc, But my program mess the 6th item, and after 10 items just crashes. can you help me find my error here? Thanks!

#include <stdio.h>
#include <stdlib.h>
#define K 5
int main(){
    int counter=0;
    int enteredNum;
    int *p=malloc(K*sizeof(int));
    int *pmore=NULL;
    printf("Please enter the series : \n");
    scanf("%d",&enteredNum);
    while(enteredNum!=0){
            p[counter]=enteredNum;
            if(counter%K==0&&counter!=0){
                pmore=malloc(((counter)+K)*sizeof(int));

                for(int i=0;i<counter;i++){
                    pmore[i]=p[i];
                //for
                free(p);
                p=pmore;
                pmore=NULL;
            }//if
            counter++;
            scanf("%d",&enteredNum);
    }


    for(int i=0;i<counter;i++)
        printf("%d\t",p[i]);
}
1
  • 1
    If counter is 6 the first time you first write to the array and then create a new one that fits the element in. You're "lucky" you didn't cause it to crash on the 6th element. Move the p[counter] after the if and before the counter++ Commented Jan 26, 2017 at 11:37

1 Answer 1

2

You set p[counter] before you enlarge p. So when K is 5, counter%K won't be zero until counter is 5, but by then it's too late, you've already stored six elements in p (0, 1, 2, 3, 4, and 5), which only had enough space for 5.

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.