21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The mlock( ) system call on Unix imposes an additional limitation over VirtualLock( )<br />

on Window: the process making the call must have superuser privileges. In addition,<br />

when fork( ) is used by a process that has locked memory, the copy of the memory in<br />

the newly created process will not be locked. In other words, child processes do not<br />

inherit memory locks.<br />

13.4 Using Variable Arguments Properly<br />

<strong>Problem</strong><br />

You need a way to protect a function that accepts a variable number of arguments<br />

from reading more arguments than were passed to the function.<br />

Solution<br />

Our solution for dealing with a variable number of arguments is actually two solutions.<br />

The interface for both solutions is identical, however. Instead of calling va_<br />

arg( ), you should call spc_next_varg( ), listed later in this section. Note, however,<br />

that the signature for the two functions is different. The code:<br />

my_int_arg = va_arg(ap, int);<br />

becomes:<br />

spc_next_varg(ap, int, my_int_arg);<br />

The biggest difference from using variable argument functions is how you need to<br />

make the calls when using this solution. If you can guarantee that your code will be<br />

compiled only by GCC and will always be running on an x86 processor (or another<br />

processor to which you can port the first solution), you can make calls to the function<br />

using spc_next_varg( ) in the normal way. Otherwise, you will need to use the<br />

VARARG_CALL_x macros, where x is the number of arguments that you will be passing<br />

to the function, including both fixed and variable.<br />

#include <br />

#include <br />

#if defined(__GNUC__) && defined(i386)<br />

/* NOTE: This is valid only using GCC on an x86 machine */<br />

#define spc_next_varg(ap, type, var) \<br />

do { \<br />

unsigned int __frame; \<br />

__frame = *(unsigned int *)__builtin_frame_address(0); \<br />

if ((unsigned int)(ap) = = __frame - 16) { \<br />

fprintf(stderr, "spc_next_varg( ) called too many times!\n"); \<br />

abort( ); \<br />

} \<br />

(var) = va_arg((ap), (type)); \<br />

Using Variable Arguments Properly | 709<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!