Browse Category: Programming

Printing STL objects while debugging C++ codes with GDB

As one can easily observe, it is not possible to print the values of STL class objects like maps, vectors, etc, while debugging a C++ code with GDB. However, it can be done by a simple hack: There is a gdb script called stl-views-1.0.3.gdb, which contains functions to print various STL container classes. One can use functions such as pmap, pvector, plist, etc, to print map, vector and list objects while debugging.

For this, we need to put the stl-views-1.0.3.gdb script file in ~/.gdbinit folder or we can load it manually from gdb by using the command:

gdb prompt>> source <some path>/stl-views-1.0.3.gdb

In the latest versions of gdb, python support is included. Hence, one can also use python scrips to perform similar tasks for which inbuilt support is not there in gdb. However, for this specific problem the above solution proves to be a quick way.

error: ‘ptrdiff_t’ was not declared in this scope

You will see this error while compiling sources of many packages. This is due to the changes in the recent version of the gcc compiler (for example when you migrate from ubuntu 12.04 to ubuntu 14.04).

To bypass this problem add std:: namespace to ptrdiff_t . That is replace ptrdiff_t with std::ptrdiff_t and there should be no problems given that you have included all the necessary headers.

However, instead of adding an std:: to all the occurrances of ptrdiff_t, one can also use the line using std::ptrdiff_t; at the beginning of the source file.

Yael Library: ‘Segmentation Fault’ while running kmeans algorithm

Yael is a library of highly optimized, multi-threaded implementations of some computationally demanding problems like clustering and nearest neighbor search. Several common vector and matrix operations are also provided in the library.

Sometimes, I found that there is a “Segmentation Fault” error while running the kmeans algorithm from Yael. This particularly occurs while using the hierarchical kmeans algorithm. The problem can be solved very simply in two steps:

1) Go to the file kmeans.c in the yael source and find the function called “random_init” which is usually the first function in that file. It should look something like this:

static void random_init(long d, int n, int k, const float * v, int * sel, 
                        unsigned int seed) {
  int *perm=ivec_new_random_perm_r(n,seed);
  ivec_cpy(sel,perm,k);
  free(perm);
}

2) Replace the whole function with the following code:

static void random_init(long d, int n, int k, const float * v, int * sel, 
                        unsigned int seed) {
  int *perm;
  if(n<k)
        perm=ivec_new_random_perm_r(k,seed);
  else
        perm=ivec_new_random_perm_r(n, seed);

  ivec_cpy(sel,perm,k);
  free(perm);
}

Voila!! Your code should be running seamlessly now.