samedi 1 avril 2017

aligned_alloc memory block in a copy assignment constructor crashes while being freed

I am maintaining some legacy code which was missing a copy assignment constructor in a managed Aligned Pointer class. I added one as follows (simplified view):

#include <iostream>
#include <cstring>
#include <stdlib.h>

template <class T, unsigned AlignB> 
class AlignedPtr {
private:
    T *mpBlock;
    unsigned mBlkSize;
public:
    // Size specific Ctor
    AlignedPtr(unsigned uNum) : 
    mpBlock(static_cast<T*>  (aligned_alloc(uNum*sizeof(T),  AlignB))),
    mBlkSize(uNum) {}
    // Default, empty Ctor
    AlignedPtr(void) : mpBlock(nullptr), mBlkSize(0) {}
    // Copy Assignment Ctor
    AlignedPtr& operator=(const AlignedPtr& x)
    {
        T *mpNewBlock(static_cast<T*>(aligned_alloc(x.mBlkSize*sizeof(T), AlignB)));
        for (size_t index=0; index < x.mBlkSize; index++) {
            mpNewBlock[index] = x.mpBlock[index];
        }
        free(mpBlock);
        mpBlock  = mpNewBlock;
        mBlkSize = x.mBlkSize;
        return *this;
    }
    // Destroy managed pointer
    ~AlignedPtr() {
        free(mpBlock);
    }
};

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

    AlignedPtr<float, 16> first_ptr;
    std::cout << "Pointer Initialized" << std::endl;

    first_ptr = AlignedPtr<float, 16>(8);
    std::cout << "Pointer Re-initialized" << std::endl;

    return 0;
}

My expectation was that the program will terminate normally, however I saw AlignedPtr Dtor fail when first_ptr goes out of scope (main termination). I compile above without any optimizations as:

g++ -std=c++11 -g aligned_alloc_bug.cpp -o aab

On a Ubuntu 14.04 with g++ 4.8.2 and get the following run-time error:

Pointer Initialized
Pointer Re-initialized
*** Error in `./aab': free(): invalid next size (fast): 0x0000000001cf9080 ***
Aborted (core dumped)

Interestingly when I replace aligned_alloc with malloc or posix_memalign for that matter program terminates correctly. Is this a bug in aligned_alloc or am I missing something basic?

P.S: 1) I did a brief search for a gcc bug which returned false. 2) Advise to avoid managing raw pointers is acknowledged in advance but I would appreciate any help for the problem at hand.

std type_traits conflict with Qt type_traits

I have Qt 5.8 installed and i get this error. I also have CONFIG += c++14 in my pro file and i also tried with c++11.

/usr/include/x86_64-linux-gnu/qt5/QtCore/qtimer.h:106: error: ‘is_same’ is not a member of ‘QtPrivate’!QtPrivate::is_same<const 

also

/usr/include/c++/5/type_traits:958: note:   ‘std::is_same’
     struct is_same;

How to get the href value in c++ using regex?

I want to fetch the value of href in c++, but my code is not giving the desired result

#include <fstream>
#include <iostream>
#include <string>
#include <regex>


int main()
{

   std::regex url("/.*(href=')(.*)('>)/");
  std::string url_test = "hjsh.ppt";
    std::ifstream file("in.txt");
    if (!file.is_open())
    {
        std::cerr << "Failed to open file!\n";
        return -1;
    }


    const std::string needle = "href";


    while (std::getline(file, url_test))
    {
        if (url_test.find(needle) != std::string::npos)
        {
          if(regex_match(url_test, url)){}
            std::cout << url_test << "\n";

        }
    }
}

The above code prints whole line as

<a href="11_custom_io.ppt">Ch11: Customizing I/O</a>

I want only 11_custom_io.ppt , name of the file. Please Help.

Lambda expressions, concurrency and static variables

As far as I know, such use of static storage within lambda is legal. Essentially it counts number of entries into the closure:

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>


typedef std::pair<int,int> mypair;

std::ostream &operator<< (std::ostream &os, mypair const &data) {
    return os << "(" << data.first << ": " << data.second << ") ";
}

int main()
{
    int n;
    std::vector<mypair> v;
    std::cin >> n;
    v.reserve(n);

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        static int i = 0;
        std::cin >> x.second;
        x.first = i++;
    });

    std::for_each(std::begin(v), std::end(v), [](mypair& x) {
        std::cout << x;
    });

    return 0;
}   

Let assume I have a container 'workers' of threads.

std::vector<std::thread> workers;
for (int i = 0; i < 5; i++) {
    workers.push_back(std::thread([]() 
    {
        std::cout << "thread #" << "start\n";
        doLengthyOperation();
        std::cout << "thread #" << "finish\n";
    }));
}

Provided I join them using for_each and the stored variable in question must count number of active tasks, not just number of entries, what possible implementations for such counter are there, if I want to avoid to rely onto global variables to avoid someone else messing up with it and allowing automatic support for separate "flavors" of threads.

std::for_each(workers.begin(), workers.end(), [](std::thread &t) 
    {
        t.join();
    });

"non-static" error in use of ROS publisher class inside of QThread class

I'm using ROS platform and want to publish a variable from publisher class. When I use this variable inside of QThread it faces with below error:

error: invalid use of non-static data member ‘MainWindow::chatter_pub’ros::Publisher chatter_pub;

My code is like this:

mainWindow.h

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

    ~MainWindow();

    class Thread : public QThread {
    public:
        void run();
    };

private:
    Ui::MainWindow *ui;
    ros::NodeHandle nh_;
    ros::Publisher chatter_pub;
    Thread thread;
};

mainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
  chatter_pub = nh_.advertise<visualization_msgs::Marker>("chatter", 10);
}

void MainWindow::on_open_cam_indoor_clicked()
{
  thread.start();
}

void MainWindow::Thread::run()
{
  while (true)
  {
    ...

    chatter_pub.publish(myVariableWantToSend);

    ...
  }
}

The main question is how can I use publisher method inside of QThread without any errors and problems. Thanks a lot...!

Should *all* function templates be passed as rvalue?

I can't help but notice that all people writing templates for functions use rvalue references. I'm not sure I'm right, but it's a tendency I noticed. Here's my simple example:

void waitForEstablished(int check_period_in_ms, SyncFunc&& syncFunc)
{
    auto established_future = promise_established.get_future();
    while (established_future.wait_for(std::chrono::milliseconds(check_period_in_ms)) != std::future_status::ready)
    {
        syncFunc();
    }
    established_future.get();
}

Explanation of this function: In this function, I provide a waiting method for the user, and provide a mechanism for synchronization/refreshing of a GUI. It helps in separating concerns. The user provides the function that should be called every check_period_in_ms milliseconds to keep prevent things from blocking. This is useful for the case when in a GUI application, the following is how I call this:

commThreadController.waitForEstablished(10,[this](){QApplication::processEvents();});

The function QApplication::processEvents() processes the GUI event loop.

But I'm really puzzled on what kind of reference I should use (always rvalue? when should it be something else?) and whether it makes a difference in any extreme case.

Should I be passing all function templates by rvalue reference?

How use integer_sort from boost library?

I use boost::sort() from boost/range/algorithm.hpp but is really... slow and I'm just working with unsigned integer type, so I thought "Maybe using integer_sort() from boost/sort/spreadsort/integer_sort.hpp I can improve the speed" The Question is that std::sort(v.begin(), v.end()) run in ~54 seconds and boost:sort(v) in ~54 seconds (Same time)

But I Write something like radix sort, and takes ~28 seconds, but I think that integer_sort can be more optimized that my code, but I don't know how use integer_sort.

#include <vector>
#include <boost/range/algorithm.hpp>
#include <boost/sort/spreadsort/integer_sort.hpp> // I WANT USE THIS
#include "myLib.hpp"

using namespace std;

int main(void)
{
  vector <unsigned> v(20);

  for (unsigned i = 0; i < v.size(); i++)
    v[i] = rand() % 1000;

  imprime(v); // THIS PRINTS THE VECTOR
  boost::sort(v); // THIS SORT THE VECTOR
  imprime(v);
  integer_sort(v.begin(), v.end()); // THIS DOES'T WORK

  return 0;
}

If I try with integer_sort(v.begin(), v.end()); I get

sort.cpp: In function ‘int main()’:
sort.cpp:23:34: error: ‘integer_sort’ was not declared in this scope
   integer_sort(v.begin(), v.end());
                                  ^
sort.cpp:23:34: note: suggested alternatives:
In file included from sort.cpp:5:0:
/usr/include/boost/sort/spreadsort/integer_sort.hpp:173:15: note:   ‘boost::sort::spreadsort::integer_sort’
   inline void integer_sort(RandomAccessIter first, RandomAccessIter last,
               ^~~~~~~~~~~~
In file included from /usr/include/boost/sort/spreadsort/integer_sort.hpp:26:0,
                 from sort.cpp:5:
/usr/include/boost/sort/spreadsort/detail/integer_sort.hpp:482:5: note:   ‘boost::sort::spreadsort::detail::integer_sort’
     integer_sort(RandomAccessIter first, RandomAccessIter last, Div_type,
     ^~~~~~~~~~~~

I know that this has something to do with the (v.begin(), v.end()) RandomAccessIter first <- I get something similar when I try std::sort(v) <- this is not correct. But I don't understand the error message. Don't say candidate expects 3 arguments, 1 provided like in std::sort.

So How use integer_sort()?

Boost Doc Says:

Each of integer_sort, float_sort, and string_sort have 3 main versions: The base version, which takes a first iterator and a last iterator, just like std::sort:

integer_sort(array.begin(), array.end());
float_sort(array.begin(), array.end());
string_sort(array.begin(), array.end());