Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangers of pointers

Tags:

c

pointers

I'm trying to learn C. Since I have already some familiarity with higher level languages (PHP, Javascript, Python) I feel most of the work I have to do involves learning how to replace structures which I would give for granted (say variable sized arrays) through the use of pointers, and manually managing memory. My problem is that I am a bit worried about playing with pointers.

Usually I try to experiment with other language features, but my problem is that a bad use of pointers could have unexpected results. In particular: is it possible - if I make a mistake - that I may corrupt memory segments that other programs are using, causing those programs to misbehave? Or will the operating system, (in my case various flavours of Ubuntu) prevent me to intefere with the memory assigned to different processes?

In the former case I guess it would be possible (though unlikely) that I may cause other programs to write bad data on the disk, corrupting some information I have on the hard drive. Or even worst (and even more unlikely, I guess) it could damage some hardware - for instance older monitors could be burned by software which would set an out of range refresh rate.

I know that probably my worries are not justified, but I would like to know how far the compiler/operating system will prevent me from doing dangerous operations when I make a mistake managing pointers.

like image 487
Andrea Avatar asked Dec 01 '22 03:12

Andrea


1 Answers

In particular: is it possible - if I make a mistake - that I may corrupt memory segments that other programs are using, causing those programs to misbehave?

Not on most (all?) major operation systems available today. Memory protection has been a feature of most Unix/Linux systems, Windows, and Mac OS for a decade. Memory protection is an OS level access control system that prevents programs writing to memory that doesn't belong to them. This is both, as you suggest, to prevent software writing into memory that belongs to other processes, but also to prevent software from reading memory that doesn't belong to it (a major security risk).

That's not to say it's something you may not have to worry about in the future, but if you're starting off learning C on a modern desktop it's something you shouldn't really think about. If you make a mistake in your C code you're probably not going to cripple the OS! :)

It's a very interesting topic, and one I think everyone would benefit from knowing about. You'll almost certainly run into situations when you're learning when you try to access memory that doesn't belong to you and your process is terminated by the system. Check out these two wiki articles for more information:

http://en.wikipedia.org/wiki/Buffer_overflow and http://en.wikipedia.org/wiki/Memory_protection

like image 97
lxt Avatar answered Dec 05 '22 06:12

lxt