On 28 Feb 2015, at 6:26 am, Gabriela Gibson <[email protected]> wrote:
>
> Hi All,
>
> Because I'm not quite sure what is all needed and to make this easier to
> discuss, I put the entire lot into a standalone proggy.
>
> Let me know if anything is missing or should be different, I commented the
> code where I was not sure about certain things.
>
> My output is listed below the code.
>
> thanks,
>
> G
>
> Ps.: the string ": Cannot allocate memory" just pops up, I don't know where
> from, maybe stderr?
>
> [[
> #define _GNU_SOURCE /* See feature_test_macros(7) */
Why is this necessary?
> #include <sys/types.h>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <stdarg.h>
> #include <time.h>
> #include <unistd.h>
>
> void *xmalloc(size_t size)
> {
> void *ptr = malloc(size);
>
> if (ptr == NULL) {
> perror("xmalloc: out of memory.\n");
> /* _exit(EXIT_FAILURE); // commented out for testing */
> return NULL;
> }
>
> return ptr;
> }
The only way to test if a process exits is to launch a sub-process, run the
test in the child, and have the parent monitor it. Under Linux/Unix, this is
done using fork() and waitpid(). However Windows provides a separate API, so
this could not be done in a cross-platform manner.
An alternative would be to have a #define exit (or #define _exit; not sure why
you used the latter) so that you can do #define exit test_exit_function and
then implement the latter to record that “exit” has been called, then later
test that.
I would also recommend calling abort() instead of exit.
I know I’m going to get chastised for saying this, but given the level of
simplicity of these functions and the complexity of writing tests for them
(they’re special cases, due to the involvement of both process management and
resource exhaustion), I don’t think we really need tests for these functions. I
know automated tests are important - and I’ve written thousands of them myself
- but there’s a point at which something becomes too trivial to warrant tests.
If there’s a problem with any of these functions, we’ll find out about it,
because literally every other test relies on them working correctly.
>
> void xfree(void *ptr)
> {
> if (ptr == NULL)
> return;
> free(ptr);
> ptr = NULL;
> }
Free always accepts NULL, and there’s no way it can fail (except for memory
corruption, which there’s no way to catch) so xfree is redundant.
Assigning ptr = NULL also does nothing, because it only modifies the ptr
variable in the scope of the function. It does not in any way affect the
variable that was passed to xfree.
—
Dr Peter M. Kelly
[email protected]
PGP key: http://www.kellypmk.net/pgp-key <http://www.kellypmk.net/pgp-key>
(fingerprint 5435 6718 59F0 DD1F BFA0 5E46 2523 BAA1 44AE 2966)