C++


C/C++: Perform safe sprintf 1

The following function accepts the address of a char * buffer, the formatting string for printf along with all the parameters needed to fill the formatting string and updates the location of the buffer to point at the final formatted string.

[download id=”2418″]

This code does not require the user to perform malloc before filling in the buffer. Using vsnprintf (variation of snprintf for variable arguments) it will automatically find the correct size that the buffer should have, allocate the space, switch the pointer of the buffer and prepare the final string using the formatting arguments.

In our header file, we used the following pre-processor directives around our declarations

#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif

to allow c++ code to call our function.

[download id=”2418″]

Source file (string_helpers.c)


#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "string_helpers.h"

int safe_sprintf(char ** buffer, const char *format, ...) {

  va_list arguments;
  //The va_start(va_list arguments, last) macro initializes and must be called first.
  //The argument last is the name of the last argument before the variable argument list, that is, the last argument of which the calling function knows the type.
  va_start (arguments, format);

  //Upon successful return, vsnprintf returns the number of characters printed (excluding the null byte used to end output to strings).
  //For that reason we add one at the end of the length.
  const int length = vsnprintf(NULL, 0, format, arguments) + 1;

  //Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function.
  // After the call va_end(arguments) the variable arguments is undefined.
  // Multiple traversals of the list, each bracketed by va_start() and va_end() are possible. va_end() may be a macro or a function.
  va_end (arguments);

  if (*buffer) {
    free(*buffer);
  }
  if (!(*buffer = malloc(length * sizeof(char)))) {
    return EXIT_FAILURE;
  }

  va_start(arguments, format);
  vsnprintf(*buffer, (size_t) length, format, arguments);
  va_end (arguments);

  return EXIT_SUCCESS;
}

Header file (string_helpers.h)


#ifndef GM_S_LITTLE_HELPERS_STRING_HELPERS_H
#define GM_S_LITTLE_HELPERS_STRING_HELPERS_H

#ifdef __cplusplus
extern "C" {
#endif

int safe_sprintf(char ** buffer, const char *format, ...);

#ifdef __cplusplus
}
#endif

#endif //GM_S_LITTLE_HELPERS_STRING_HELPERS_H

Usage example (main.cpp)


#include <iostream>
#include "string_helpers.h"

int main() {

  char * buffer;
  safe_sprintf(&buffer, "Hello, World!\nFrom Line %d in function %s of the file %s.", __LINE__, __func__, __FILE__);
  printf("%s", buffer);
  return 0;
}

[download id=”2418″]


C/C++: Set Affinity to process thread – Example Code 3

The following code sets the affinity of the process thread to a specific CPU core.
In this example, we define the CPU core id using the variable core_id.

Full source code available here [download id=”2363″]


#include <stdio.h>
#include <stdlib.h>
#define __USE_GNU
#include <sched.h>
#include <errno.h>
#include <unistd.h>

// The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong.
#define print_error_then_terminate(en, msg) \
  do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)


int main(int argc, char *argv[]) {

  // We want to camp on the 2nd CPU. The ID of that core is #1.
  const int core_id = 1;
  const pid_t pid = getpid();

  // cpu_set_t: This data set is a bitset where each bit represents a CPU.
  cpu_set_t cpuset;
  // CPU_ZERO: This macro initializes the CPU set set to be the empty set.
  CPU_ZERO(&cpuset);
  // CPU_SET: This macro adds cpu to the CPU set set.
  CPU_SET(core_id, &cpuset);

  // sched_setaffinity: This function installs the cpusetsize bytes long affinity mask pointed to by cpuset for the process or thread with the ID pid. If successful the function returns zero and the scheduler will in future take the affinity information into account. 
  const int set_result = sched_setaffinity(pid, sizeof(cpu_set_t), &cpuset);
  if (set_result != 0) {

    print_error_then_terminate(set_result, "sched_setaffinity");
  }

  // Check what is the actual affinity mask that was assigned to the thread.
  // sched_getaffinity: This functions stores the CPU affinity mask for the process or thread with the ID pid in the cpusetsize bytes long bitmap pointed to by cpuset. If successful, the function always initializes all bits in the cpu_set_t object and returns zero.
  const int get_affinity = sched_getaffinity(pid, sizeof(cpu_set_t), &cpuset);
  if (get_affinity != 0) {

    print_error_then_terminate(get_affinity, "sched_getaffinity");
  }

  // CPU_ISSET: This macro returns a nonzero value (true) if cpu is a member of the CPU set set, and zero (false) otherwise. 
  if (CPU_ISSET(core_id, &cpuset)) {

    fprintf(stdout, "Successfully set thread %d to affinity to CPU %d\n", pid, core_id);
  } else {

    fprintf(stderr, "Failed to set thread %d to affinity to CPU %d\n", pid, core_id);
  }

  return 0;
}

To compile we used the following command

gcc -Wall affinity.c -o affinity;

Full source code available here [download id=”2363″]

For a full pthread example please visit this link.


C/C++: How NOT to define multiple pointers

When defining pointers in C/C++ you should be careful on how you use the * characters. If you try to define multiple pointers on the same line and you do not add the * character in front of each variable, then the results will not be what you would expect. In the following examples we added the * to the data type definition, hoping that all variables would become pointers of that data type. Unfortunately, as the compiler points out later on while making the comparisons, only the first variable in each line becomes a pointer of the data type.

Wrong Examples

C Source Code:

#include <stdio.h>

int main()
{
    int* a, b;
    int *c, d;
    int * e, f;

    a == b;
    c == d;
    e == f;

    return 0;
}

Compiler Output:

$ gcc -o main *.c                                                                                          
main.c: In function 'main':                                                                                      
main.c:9:7: warning: comparison between pointer and integer                                                      
     a == b;                                                                                                     
       ^                                                                                                         
main.c:10:7: warning: comparison between pointer and integer                                                     
     c == d;                                                                                                     
       ^                                                                                                         
main.c:11:7: warning: comparison between pointer and integer                                                     
     e == f;                                                                                                     
       ^                                                                                                         

C++ Source Code:

#include <iostream>
using namespace std;

int main()
{
    int* a, b;
    int *c, d;
    int * e, f;

    a == b;
    c == d;
    e == f;

   return 0;
}

Compiler Output:

$ g++ -std=c++11 *.cpp -o main

main.cpp: In function ‘int main()’:
main.cpp:10:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
     a == b;
          ^
main.cpp:11:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
     c == d;
          ^
main.cpp:12:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
     e == f;
          ^

Correct Examples

#include <stdio.h>

int main()
{
    int* a, * b;
    int *c, *d;
    int * e, * f;

    a == b;
    c == d;
    e == f;

    return 0;
}
#include <iostream>
using namespace std;

int main()
{
    int* a, * b;
    int *c, *d;
    int * e, * f;

    a == b;
    c == d;
    e == f;

   return 0;
}

C++: Get size of enum 1

We used the following application in C++ to test the size of an enum:

#include <iostream>
using namespace std;

enum SINGLE {
        S_ZERO = 0x0,
        S_FULL = 0xFFFFFFFF
};

enum DOUBLE {
        D_ZERO = 0x0,
        D_FULL = 0xFFFFFFFFFFFFFFFF
};

int main() {
        cout << "Single Zero: Size '" << sizeof(S_ZERO) << "' Value '" << S_ZERO << "'" << endl;
        cout << "Double Zero: Size '" << sizeof(D_ZERO) << "' Value '" << D_ZERO << "'" << endl;

        cout << "Single Full: Size '" << sizeof(S_FULL) << "' Value '" << S_FULL << "'" << endl;
        cout << "Double Full: Size '" << sizeof(D_FULL) << "' Value '" << D_FULL << "'" << endl;
        return 0;
}

The output we got is the following:

Single Zero: Size '4' Value '0'
Double Zero: Size '8' Value '0'
Single Full: Size '4' Value '4294967295'
Double Full: Size '8' Value '18446744073709551615'

From the result it is pretty easy to understand that the size of an enum will grow to 64bit when any of its values is greater than 32bit.

For our test we used g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6) on a 64bit Fedora 23.