What are security issues in the C language?

What are security issues in the C language?


I recently read about two of them:

1.  Buffer Overflow:  It happens when data written to a buffer (chunk of memory) overflows and gets overwritten onto the adjacent memory due to lack of proper boundary checks. Let me show you something - consider the following code that I tried on Compile and Execute C Online, (An Online C Compiler):









You can clearly see that I have allocated memory for only 8 integers in the array 'a', but I have tried to access and modify the value corresponding to 10th integer in array 'a' (a memory location that belongs to some other entity). Certainly, anything this unethical must not be allowed, right guys... but the output is quite surprising, isn't it:

Then, I got a little more ambitious and tried the following:







and I got the utmost feared segmentation fault:



So, what happened ?

Well, C will allow a program to modify a memory as long as it belongs to the same program. In case of a[9] the memory location belonged to the program, but in case of a[10000] it did not. 
(Note that even though the memory location a[9] belonged to the program and could be modified, it was not a good practice to do so, because it simply means that you are corrupting some other information stored by the program.)

2. Double Free Call: As the name suggests, it occurs when you try to free the memory allocated to a pointer, that has already been freed. Let us see something cool:


(Above code was compiled and executed on Compile and Execute C Online, (An Online C Compiler))

So, what's the problem, seems pretty fine to me ?

The problem, my dear folks, is that once you have freed the pointer 'a', you don't know if its new value is 'NULL' or does it point to some other location. If it does point to some other location, which it may, then it can also free that memory. 

I, then, tried to see, if a freed pointer is always automatically set to 'NULL', but it seems like not:








But fear not folks, for the whole of this world is not filled with darkness, and there is still some hope. The code where I tried to free the same pointer twice without reassignment did throw me an error with the message -"double free or corruption".  Phew !....., looks like this one has been taken care of.

(p.s: I would like to know about more vulnerabilities in C, it would be great if others could share them here.)

-----

Edit: After a comment , I decide that I must add to my answer that the second error (double free call) can actually be avoided by resetting the once freed pointer to NULL. For e.g. see below:




and the output:


(Above code was compiled and executed on Compile and Execute C Online, (An Online C Compiler

Thank you so much for reading this blog....

Ritchie shiva

Comments

Popular posts from this blog

Cloud Computing?

C And C++ Programming Languages — Biggest Differences