cmocka free operation and catching exceptions - c

I started my adventure with cmocka library, and I have two questions.
Is it possible to find out if free() operation was made correctly? I mean, I would like to test function which is cleaning up tree structure. I've read about test_free(), but honestly I don't understand idea behind that.
The second thing is case of catching standard library exceptions. I know about function expect_assert_failure, but how to use it? For example I would to do something what will throw segmentation fault, but I would like to pass test anyway.

You need to add
#define UNIT_TESTING 1
before you include the cmocka.h header file, then malloc, realloc and free get overridden and will warn you about memory leaks.
expect_assert_failure() if for checking that an assert() condition is really hit.

I'd suggest just doing an additonal test with valgrind.
valgrind --error-exitcode=1 ./test
Without the option valgrind would always return the same exit code returned by your test program. This way if your test program succeeds, but valgrind's memory check reveals errors, it will return 1 to indicate an error.

Related

What can make dlclose() fail?

On a POSIX (or GNU) system, what can make the dlclose() function fail?
I know that it fails on repeat-close; and that it misbehaves on a null pointer argument (got a segmentation violation on my system). But are there other situations it can fail?
Edit: I tried looking at the source code and was kind of stumped - could not really figure out where to look (dlclose.c is not the place apparently).
The actual implementation is here.
Look for calls to _dl_signal_error() -- there are two.

warning for not using free() malloc

Are there any safeguards built into GCC that check for memory leaks? If so how can I use them? When I compile with "gcc -Wall -o run run.c", the compiler does not seem to care if any allocated heap-space is being freed at the end of the code. I could not find any simple fixes for this on Google.
Thanks much for your time.
EDIT:
Google Searches did point to Valgrind among other tools. But I was curious as to why the compiler cant deal with this issue. As a newbie, it seemed a simple enough task to check if every "malloc" has a "free" associated with it.
There are two ways to analyze code for problems - static analysis and run-time analysis. Static analysis reads the code - this is what compilers do really well. Run-time analysis for code problems happens when the code is linked against another set of libraries that see what the code actually does as it runs under surveillance. Finding memory leaks is difficult for static analysis but not for a run-time analysis package.
Other run-time analyses are things like code coverage - does all parts of your code run? gcov does this, like valgrind and electric fence look for memory problems like leaks.
So, no, there are no really good compiler safeguards for testing memory leaks.
There is -fsanitize=leak GCC flag.
It overrides malloc/calloc/free to make them count allocated and freed blocks of memory.
If your program is compiled with this flag, it prints information about detected leaks to the terminal after execution.
You can read about it here and here.
Also, I have never used it, so this answer is completely based on GCC manual.

Is there a Windows API memory allocator/deallocator I can use that will just give me an error code if something goes wrong & in a cross-compiler way?

This is probably a crazy question but:
For the purposes of debugging and error handling I'd like to be able to make a note of why an allocation or free call failed. I'd like the same code to be compilable by both Microsoft's C compilers and MinGW-w64 (but not other MinGWs).
I could use malloc()/realloc()/free() but they don't provide any defined method of getting an error other than ENOMEM. Or is it safe to assume that the only reason malloc() can fail is lack of memory, which HeapAlloc() and others seems to disagree with? (This will also stop being an option if I choose not to use the C runtime in any future DLLs.) Or is it safe to assume that errno has any other error code? I would need to check my standards again...
I could also use HeapAlloc()/HeapReAlloc()/HeapFree(), but they don't return a last-error code. Instead, they can be made to throw an exception, which you are supposed to catch with a __try block... which is not supported by MinGW. libseh is not an option here; my programs and DLLs should be freestanding. I'm going to assume it is not safe to assume that the only reason it can fail when set to not throw an exception is out of memory because heap corruption is listed as a possibility; is this correct?
I tried using LocalAlloc()/LocalReAlloc()/LocalFree() but it failed to allocate more than a 256-byte-or-so structure and 2 ints, returning ERROR_NOT_ENOUGH_MEMORY.
There's no VirtualReAlloc(), so I assume I would need to write my own malloc() implementation if I go the VirtualAlloc() route.
Or am I just being crazy about all this?
And what about other allocators that I would be required to use, such as SysAllocString(); would it be safe to assume those can only ever fail because of out of memory?
Thanks.

Can I make valgrind ignore glibc libraries?

Is it possible to tell valgrind to ignore some set of libraries?
Specifically glibc libraries..
Actual Problem:
I have some code that runs fine in normal execution. No leaks etc.
When I try to run it through valgrind, I get core dumps and program restarts/stops.
Core usually points to glibc functions (usually fseek, mutex etc).
I understand that there might be some issue with incompatible glibc / valgrind version.
I tried various valgrind releases and glibc versions but no luck.
Any suggestions?
This probably doesn't answer your question, but will provide you the specifics of how to suppress certain errors (which others have alluded to but have not described in detail):
First, run valgrind as follows:
valgrind --gen-suppressions=all --log-file=valgrind.out ./a.out
Now the output file valgrind.out will contain some automatically-generated suppression blocks like the following:
{
stupid sendmsg bug: http://sourceware.org/bugzilla/show_bug.cgi?id=14687
Memcheck:Param
sendmsg(mmsg[0].msg_hdr)
fun:sendmmsg
obj:/usr/lib/libresolv-2.17.so
fun:__libc_res_nquery
obj:/usr/lib/libresolv-2.17.so
fun:__libc_res_nsearch
fun:_nss_dns_gethostbyname4_r
fun:gaih_inet
fun:getaddrinfo
fun:get_socket_fd
fun:main
}
Where "stupid sendmsg bug" and the link are the name that I added to refer to this block. Now, save that block to sendmsg.supp and tell valgrind about that file on the next run:
valgrind --log-file=valgrind --suppressions=sendmsg.supp ./a.out
And valgrind will graciously ignore that stupid upstream bug.
As noted by unwind, valgrind has an elaborate mechanism for controlling which procedures are instrumented and how. But both valgrind and glibc are complicated beasts, and you really, really, really don't want to do this. The easy way to get a glibc and valgrind that are mutually compatible is to get both from the Linux distro of your choice. Things should "just work", and if they don't, you have somebody to complain to.
Yes, look into Valgrind's suppression system.
You probably want to ask about this on the Valgrind user's mailing list (which is extremely helpful). You can suppress output from certain calls, however, suppressing the noise is all you are doing. The calls are still going through Valgrind.
To accomplish what you need, you (ideally) match Valgrind appropriately with glibc or use the macros in valgrind/valgrind.h to work around them. Using those, yes, you can tell valgrind not to touch certain things. I'm not sure what calls are borking everything, however you can also (selectively) not run bits of code in your own program if its run under valgrind. See the RUNNING_ON_VALGRIND macro in valgrind/valgrind.h.
The other thing that comes to mind is to make sure that Valgrind was compiled correctly to deal with threads. Keep in mind that atomic operations under Valgrind could cause your program to crash during racey operations, where it otherwise might not, if not properly configured.
If you have been swapping versions of valgrind and glibc, there's a chance you found a match, but incorrectly configured valgrind at build time.

Using callback functions for error handling in C

I have been thinking about the difficulty incurred with C error handling.. like who actually does
if(printf("hello world")==-1){exit(1);}
But you break common standards by not doing such verbose, and usually useless coding. Well what if you had a wrapper around the libc? like so you could do something like..
//main...
error_catchall(my_errors);
printf("hello world"); //this will automatically call my_errors on an error of printf
ignore=1; //this makes it so the function will return like normal and we can check error values ourself
if(fopen.... //we want to know if the file opened or not and handle it ourself.
}
int my_errors(){
if(ignore==0){
_exit(1); //exit if we aren't handling this error by flagging ignore
}
return 0;
//this is called when there is an error anywhere in the libc
}
...
I am considering making such a wrapper as I am synthesizing my own BSD licensed libc(so I already have to touch the untouchable..), but I would like to know what people think about it..
would this actually work in real life and be more useful than returning -1?
during this years I've seen several attempts to mimics try/catch in ANSI C:
http://simgrid.gforge.inria.fr/doc/group__XBT__ex.html
http://llg.cubic.org/trycatch/
I think that try/catch approach is more simple than your.
But how would you be able to catch the error when it was expected? For example I might expect a file open to fail and want to deal with it in code instead of the generic error catcher.
To do this you would need two versions of every function. One that trapped errors and one the returns errors.
I did something like this long ago without modifying the library. I just created wrapper functions for common calls that did error checking. So my errchk_malloc call checked the return and raised an error if the allocation failed. Then I just used this version everywhere in place of the built in malloc.
if the goal is to exit cleanly as soon as you encounter an error that's ok... but if you want to do a minimum of error recovery, i can't see how your approach is useful...
To avoid this kind of problem, I sometimes use LD_PRELOAD_PATH to integrate my error management (only for my own projects since this is not a really good practice...)
Do you really want to change the standard behaviors of your LIBC ? You could add a few extensions around common functions.
For example, Gnome uses g_malloc and g_try_malloc. The former will abort on failure while the later will simply yield a null-pointer like malloc.

Resources