# A question about libc safeguards



## Nezmer (Feb 13, 2011)

Hi,

I might be having many misconceptions. So don't be shocked if you come by a horribly inaccurate statement in the following lines.

If I understand correctly, FreeBSD libc is built with stack protection. So It would catch buffer overflows and segfault the app that caused them.

Now, I've been trying to learn the basics of C and I decided to write a mini-app based on a library to see how far my limited knowledge can get me.

The mini-app seemed to work for most cases. But failed with buffer overflows sometimes(late in the process) and I couldn't figure out why the crashing line is causing an overflow.

It turned out that I had a very very stupid mistake in the dynamic array allocation lines(using malloc) not the crashing line (a realloc not directly related to any of the arrays, which would call malloc if the pointer is NULL).

How did I figure it out eventually?
I tested the mini-app in my GNU/Linux VPS. It failed early with:

```
*** glibc detected *** <mini-app>: malloc(): memory corruption: 0x00000000025eac20 ***
```

That happened very early in the process and that pushed me to look very hard at the malloc lines and see what's wrong with them.

If I understand correctly, GNU libc detected here the illegal (or erroneous) access of a memory location and prevented it. Which strikes me as a very good security practice.

Do we have such a safeguard in FreeBSD libc?

What safeguards in general do we have? And how do they affect performance?


----------



## expl (Feb 13, 2011)

This is more a debuging feature than a safeguard.
If you want to learn how to debug your code fast learn how to use gdb and ktrace.


----------



## Nezmer (Feb 13, 2011)

expl said:
			
		

> This is more a debuging feature than a safeguard.
> If you want to learn how to debug your code fast learn how to use gdb and ktrace.



That's true and I know both gdb and ktrace. I'm not an expert user of those tools but I know them. I know valgrind too (but I didn't need to use it yet).

My question was more along the lines of how to force a process to segfault or quit to indicate a problem that you can then investigate with your eyes(by looking at the code) or with the suitable tool. A problem that might not occur with basic testing of your application or library.

As far as I know, Those features belong to libc(the example I mentioned) and the compiler(e.g -fstack-protector). Although those features might crash harmless processes sometimes, they are good and useful for both debugging and security.

Please correct me if my understanding is far off.


----------



## expl (Feb 14, 2011)

Best solution is to use plenty of assert(3) calls in your code to check for static programming or hardware related errors.


----------

