0

Consider following code snippet(mimicking whats going on in my very large project, using some C routines in C++ code)

#include <string>
#include <iostream>
#include "stdafx.h"
struct lName
{
       std::string name;
};

void lalloc( int *nloc, lName **tst)
{
       lName *tst1;
       int bn = 2;
       tst1 = (lName*)malloc(bn * sizeof(*tst1));
       memset((void*)tst1, 0, bn * sizeof(*tst1));
       *nloc = bn;
       *tst = tst1;
}
void ltest()
{
       std::string fid = "tst";
       lName *tst, *tst1;
       int lsz;
       lalloc(&lsz, &tst);
       for (int j = 0; j < lsz; ++j)
       {
              tst1 = &tst[j];
              tst1->name = fid;
              std::cout << "fid : " << fid << " Name: " << tst1->name << "\n";
       }
}

In visual Studio 2017, the content of the tst1->name is garbage after the assignment (Its empty string prior to the assignment). However if I use tst1->name = std::string(fid);, it seems to work as expected (my understanding is that this line will create a temporary). Seems to work fine in VS2012 as well. Is there something here in the code not conforming? (The real code involves proper freeing of the memory etc)

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
user6386155
  • 825
  • 7
  • 17

0 Answers0