0

Sorry for the trouble. I've the following array list that is initialized as size 1. However i can do a scanf and loop through list[0] to list[4] without having any problem in visual studio 2010.

Isn't there supposed to have an error here?

void main()
{   
    int i=0,menu_choice=0;
    int size;
    int list[1]; //array initialized with size 1
    do{ 
        printMenu();
        printf("Enter Your Choice: ");
        scanf("%d",&menu_choice);
        switch(menu_choice){
        case 1:
            printf("\n");
            printf("Enter array size: ");
            scanf("%d",&size);
            printf("Enter %d numbers: ",size);
            for(i=0;i<size;i++)
            {
                scanf("%d",&list[i]);
            }   
            for(i=0;i<size;i++)
            {
                printf("%d",list[i]);
            }
            break;

        default :
            printf("Please select the right choice \n");
            break;
        }

    }
    while(menu_choice!=8);


}
2
  • 5
    C allows you to shoot yourself in the foot in many nice ways, like writing beyond the limits of an array. It will however lead to undefined behavior. Commented Mar 10, 2015 at 4:00
  • 1
    Move int list[1]; to be the first line in main and see how things change. Commented Mar 10, 2015 at 4:03

1 Answer 1

4

C doesn't do implicit array bounds checking like your friendly neighborhood Java does.

C will gladly let a program run off the ends of an array (or any allocated memory) when the programmer isn't careful. This leads to undefined behavior (oftentimes a memory segmentation or violation fault) and is a common attack vector for hackers (buffer overflow).

The same goes for C++ too.

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

8 Comments

Thanks bro. What if i were to put a "list[size];" directly after the "printf("Enter array size: ");" statement? Will c re-initialize the array with the right size? Or the only way is to use malloc?
@ericlee That depends on your compiler. C99 does allow that, but not all compilers implement Variable Length Arrays (VLAs), which is the name of that feature. MS Visual Studio notably does not allow VLAs AFAIK.
@jschultz410 VLAs cannot be resized
@ericlee you could do the input first, and then write int list[size]; , and then do the rest of your logic. Of course, malloc is another option.
@MattMcNabb does it mean that i'll keep the int list[1]; and than i will re-initialize it again directly after the "printf("Enter array size: ");" statement? by having list[size];?
|

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.