Home > Articles > Programming > C/C++

C/C++ Memory Management, Bit Fields, and Function Pointers

You're sure that your C/C++ memory-allocation code is bulletproof, but will the code work when the host platform is under stress? Consider using bit flags for applications that require low-level data access. Modern programming also routinely requires the use of complex language features such as callbacks and function pointers. As Stephen B. Morris explains, the use cases for these features are both simple and powerful.
Like this article? We recommend

Introduction

Every programming language has peculiarities. C and C++ are no exception! Very often, difficulties arise when a given language feature comes into close contact with a host resource; the classic case, of course, is memory allocation. It's remarkably easy to get into trouble with memory allocation. Can you be certain that a given call to malloc() succeeded?

Bit flags are a clever (but little-used) feature of C that allow for access to memory-mapped devices. But bit flags also have vagaries. In this article, I show how bit flags touch on the areas of data alignment and memory allocation.

Finally, function pointers provide a way to treat code as data. This notion is intrinsic to functional programming languages, such as Python, JavaScript, and Java 8. It's nice to see that C got in first with function pointers, and I discuss some reasons why they make sense to use in our day-to-day coding.

Let's get into some memory management.

C Memory Management

A successful call to malloc() returns a block of uninitialized memory. Data inside the block is sometimes referred to as cruft. The memory is allocated in accordance with the platform-alignment requirements, which means that the size of the block sometimes is somewhat larger than expected. No big surprises there.

Perhaps not as well known is this: The default Linux memory-allocation strategy is optimistic. This means that even when a call to malloc() returns non-null, there is no guarantee that the memory is available. I must confess to a little surprise when I first learned this fact! Imagine the consequences of a non-null semi-failed allocation for a real-time system. In this case, a non-null allocated block may in fact be too small for our needs, which means that the system might be out of memory.

If the system is out of memory, one or more processes will potentially be terminated by the Out of Memory (OOM) killer. The intrusion of the OOM killer can be further complicated if a given process leader has immunized itself against OOM-killer operations. For example, for system stability, root-level processes might not be desirable candidates for an OOM killer; a root-level process that's hogging memory might not be a candidate for eviction.

This all sounds a little complicated and scary, right? Remember that we're discussing edge cases here—memory might be scarce or heavily allocated, or the heap could be highly fragmented. However, as devices become smaller and more heavily loaded with software, we must be aware of the finer detail of memory-allocation mechanisms.

Fixing the Memory-Allocation Doubt

In a slight departure from my usual article style, let's define a requirement and see how we might go about fulfilling it in code. In the spirit of modern agile development, we'll define this requirement as a JIRA ticket. Once the ticket is created and assigned to us, we would typically set the status of the ticket to "in-progress." Once the coding is finished and tested to our satisfaction, the ticket status can be marked as fixed, and the code is pushed into a sprint delivery pipeline.

Memory Management Requirements

To make certain that all calls to malloc() are protected, our allocated block must have an expected size and a delivered size. Checking the size of an allocated block incurs a cost. This should be no surprise—most software-development decisions involve some level of cost.

The first cost element in this case is that we are (to some extent) making the code platform-specific. The second cost element is a potential speed penalty. So how should we do it? We'll use malloc_usable_size() after calling malloc() to allocate seven bytes:

void* p = malloc(7);
size_t usable = malloc_usable_size(p);
cout << "Size of malloc_usable_size for p is " << usable << endl;

This code produces the following output:

Size of malloc_usable_size for p is 12

Notice that the call to malloc() requests a size of 7, but we receive a block of size 12. The difference is intended to facilitate the platform-alignment requirement of the memory block.

What's nice about this scheme is that, at the expense of some platform-specific code and a slight speed reduction, we now know for sure whether our call to malloc() has succeeded. No more guesswork to determine whether we have a dreaded memory-edge case. At this point, we might mark the JIRA ticket as being fixed.

Updating the Work Ticket

You might argue that one thing is missing from the above code: What if the call to malloc() fails? Good point. In the spirit of agile development, it would probably be appropriate to change the status of the JIRA ticket from fixed to open (or in-progress). Then the task is reassigned to us, allowing us to fix the last issue as follows:

size_t usable = 0;
void* p = malloc(7);
if (p != NULL) {
      usable = malloc_usable_size(p);
      cout << "Size of malloc_usable_size for p is " << usable << endl;
} else {
      cout << "Memory allocation failed" << endl;
}

The updated code now verifiably allocates the required memory block. It also handles the case when the call to malloc() fails. Our stated requirement can be declared fulfilled. At this point, the JIRA ticket could be marked with a status of fixed, and we can move on to our next assigned ticket!

Of course, this assumes that we don't want to implement any unit tests for the code. In cases where a code change is very small, there may not be a pressing need for a unit test. However, as a comprehensive test for this code, we could attempt to create a real out-of-memory situation, which would allow us to verify the code in depth.

Creating an out-of-memory situation necessarily moves the work into the realm of integration/QA testing. Depending on the level of criticality of the code, we might or might not opt to deliver such test artifacts. Examples might include code that operates in a hazardous environment or in a safety-critical application.

For purposes of this article, however, we mark the JIRA ticket as being fixed.

For more on good discipline in memory management, see my eBook Five Steps To Better Multi-language Programming: Simplicity in Multi-language Coding: C/C++, Java, Bash, and Python.

A Memory Management Pattern—and Accompanying Anti-Pattern

The issue of avoiding failed memory allocations has traditionally led programmers to adopt a kind of unwritten design pattern: Allocate a memory pool when the application starts. The application code can then draw from the pool as and when needed. However, not even this pattern guarantees that the size of the allocated memory block is as expected! The best plan is to be careful and at least consider using something like malloc_usable_size().

As with all design patterns, an anti-pattern will usually make an unwelcome appearance. Memory allocation is no exception to this unwritten rule. The anti-pattern in this case is mixing the traditional C and the newer C++ allocation services by mixing calls to malloc(), new(), free(), and delete(). Mixing these calls in the same code base is a bad idea. Why? The underlying implementations may not be in harmony with each other, which can lead to unpredictable results.

Minimizing the Impact of Platform-Specific Code

It's always a good idea to ensure that any platform-specific code is placed in a single location, facilitating future changes of the host platform. When using code such as malloc_usable_size() and/or _msize(), make sure it's located inside code, something like this:

#ifdef __linux__
      size_t checkAllocatedBlock(void* ptr) {
            return malloc_usable_size(ptr);
      }
#elif _WIN32
      size_t checkAllocatedBlock(void* ptr) {
                return _msize(p);
      }
#else 
#endif

Of course, some code duplication is involved, but it illustrates the point that, depending on the value of the platform-specific symbol, we invoke only the appropriate handler. This is better than putting calls to malloc_usable_size() and/or _msize() in multiple locations in your application code. If you later change from Linux to Windows or vice versa, only a recompilation is needed.

Let's now turn our attention to another implementation-dependent language mechanism—bit fields.

Using Bit Fields for Low-Level Programming

Bit fields are often used in situations where specific bit patterns are required in memory. Typical applications for this type of code are interactions with low-level devices that use the various bit patterns as part of some sort of communication protocol. A good example is electronic smart cards and card readers. These devices communicate with each other using a simple messaging protocol, such as Europay MasterCard Visa (EMV).

One way to implement such a protocol is by using C-based bit fields, with each protocol message being encoded as a bit field structure. Then a higher-level state machine could use these message definitions to enact the required protocol exchanges.

Let's look at these interesting bit fields.

A Simple Bit Field Structure

Following is an example of a structure containing three separate bit fields:

struct {
      unsigned char is_keyword : 8;
      unsigned char is_extern : 1;
      unsigned char is_static : 1;
} flags;

flags.is_keyword = 14;
printf("flags.is_keyword %d\n", flags.is_keyword);
printf ("Bit pattern of %d = %X\n", flags.is_keyword, flags.is_keyword);

Notice the size definition at the end of each line in the struct definition. This size dictates the number of bits in the variable—in this case, 8, 1, and 1, respectively.

The output from this code is as follows:

flags.is_keyword 14
Bit pattern of 14 = E

What about the size of the struct? Let's find out:

struct {
      unsigned char is_keyword : 8;
      unsigned char is_extern : 1;
      unsigned char is_static : 1;
} flags;

flags.is_keyword = 14;
printf("flags.is_keyword %d\n", flags.is_keyword);
printf ("Bit pattern of %d = %X\n", flags.is_keyword, flags.is_keyword);
cout << "Size of flags is " << sizeof(flags) << endl;

Here's the output:

flags.is_keyword 14
Bit pattern of 14 = E
Size of flags is 2

That's interesting! Why two bytes? Well, looking at the size of the bit patterns, the compiler seems to be doing some sort of optimization. Let's test this by adding another seven-bit item to the structure:

struct {
      unsigned char is_keyword : 8;
      unsigned char is_extern : 1;
      unsigned char is_static : 1;
      unsigned char is_static2 : 7;
} flags;

Here's the updated output:

flags.is_keyword 14
Bit pattern of 14 = E
Size of flags is 3

Now we have a 3-byte size, which is as expected for a total data size of 17 bits. That is, the alignment required is on at least a byte boundary, which raises the size to 3 bytes or 24 bits on my laptop (32-bit) platform.

You probably won't have much cause to use bit fields, but they provide an easy way to do this type of low-level programming.

Let's move away from platform-specific type coding and look at another interesting area of multi-language convergence: C function pointers and Java 8 lambdas. This is the use case of passing code as data.

Callbacks: JavaScript, C Function Pointers, and Java 8 Lambdas

The traditional use case for function pointers is when you need some type of callback mechanism. In web-based front-end programming, JavaScript provides a handy way to do this as follows, in the form of a click listener function that is added to a given DOM element:

function btnAddClicked(event) {
  $event.target.preventDefault();
  $('#task').removeClass('not');
}

Now the above function is added to a DOM element with the ID btnAddIt:

$('#btnAddIt').click(btnAddClicked);

The btnAddClicked function is our callback, which gets executed when the associated front-end element is clicked. In other words, the browser executes the call, which is why it's termed a callback. That's a lot of power in just a few lines of JavaScript!

How would we code C function pointers?

C Function Pointers

Here's a simple example of a C function pointer:

double do_computation(double (*funcp)(double), double baseValue)
{
      return (*funcp)(baseValue);
}

int main() {
    double (*fp)(double);      // Function pointer
    fp = sin;
    printf("do_computation() returns: %f\n", do_computation(fp, 1.0));
}
  • The function definition takes two parameters: a function pointer and a double value. Running it produces this output:
do_computation() returns: 0.841471
  • Why would it be a good idea to use a function pointer in this way? One reason is that the called function need not be changed if a different transcendental function is required. If we require a call to cosine, for example, we change the client code as follows:
fp = cos;
printf("do_computation() returns: %f\n", do_computation(fp, 1.0));

This approach might be useful if the do_computation() function was contained in a library, or if it was otherwise impossible to change it. This is pretty similar to the Java 8 Lambda use case.

Java 8 Lambda (or Callback) Functions

Java 8 Lambdas are very useful for reducing code clutter, particularly in the case of anonymous inner classes. Here's an example of a Lambda from one of my earlier articles, "Code as Data: Java 8 Interfaces":

public class Calculator {

    interface IntegerMath {

        int operation(int a, int b);
    }

    interface RealMath {

        double operation(double a, double b);
    }

    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public double operateBinary(int a, int b, RealMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        RealMath division = (a, b) -> a / b;
        System.out.println("137 / 12 = " +
            myApp.operateBinary(137, 2, division));
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));
    }
}

Notice how the different mathematical functions are passed into the caller myApp.operateBinary(), along with the parameters.

That's three callback mechanisms from three languages. These are powerful features that are well worth learning.

Conclusion

Memory management in C and C++ continues to provide fertile ground for errors. It's interesting to note that even if a call to malloc() returns non-null, the resulting block might not be large enough for our needs. However, we can handle this issue with some platform-specific code.

Bit fields provide an alternative to explicit bit masks and have the advantage of encapsulating bit data inside structures, which helps to modularize such platform-specific code. Bit fields allow us to implement features efficiently, such as with machine-to-machine protocols.

Function pointers, a slightly neglected part of the C language, provide a means of keeping library code unchanged. This can be very important for cases in which the library code has been tested extensively, and the cost of modification and retesting is very high.

References

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020