Saturday, June 11, 2011

C : thank you for the memories

C is in general a quite free language, in a sense that it usually compiles! However, when it comes to running, even the most experienced programmers get errors or values that they wouldn't expect.
The most common error is a segmentation fault. This happens when your program tries to write or read a memory location out of its bounds, so the operating system does not allow it.
In addition, sometimes, you get some unexpected values, because you accidentally read a wrong memory location that belongs to your program, so the operating system does not block it. Furthermore,somebody can write accidentally a piece of code that might cause the program to freeze:
Imagine you want to create an array of length 10 and initialise it with 0 values.
What would happen if you write this (by mistake of course)

int main()
{
   
    int a[10];
    int i = 0;
    for (;i<=10; i++)
            a[i] = 0;
   
}



Why your program freezes? What would happen if you read the array without putting initial values in it if you print it out?
Can you guess what would happen if you read a[10]?
Try it! It's really fun!
by VasLabs

No comments:

Post a Comment