Dynamical allocation of TString : malloc (C-like) crashes, new (C++-like) : fine : why?

Hello,

For dynamical allocation, there is C-like approach with malloc, and the C+±like approach with new.

Here is a minimal program that shows that malloc works fine with native types (for example double), but for TString, it crashes.
With new, I never occur problems.

Why is there a problem with malloc for TString ?

example :

#include <iostream>
#include <TString.h>

using namespace std;

int MinimumProblemMalloc()
{
  //example of **dynamical allocation** with 4 objects of type double
  //don't say that it is useless : this is to show the approach
  double *array_doubles=(double *)malloc(4*sizeof(double));
  array_doubles[0]=3;
  array_doubles[1]=6;
  array_doubles[2]=1;
  array_doubles[3]=2;
  
  cout << "phase 1" << endl;
  //with next line, it will crashes, apart if you remove 1 'a' of the name
  TString *array_tstring=(TString *)malloc(2*sizeof(TString));
  cout << "phase 2" << endl;

  //while if you comment previous way and use instead next line, it will work
  //TString *array_tstring=new TString[2];

  array_tstring[0]="FirstMeasurement";

  cout << "phase 3" << endl;
  array_tstring[1]="Secondaaa";

  cout << "phase 4" << endl;

  return 0;
}
 

Please read tips for efficient and successful posting and posting code

_ROOT Version: 6-18-00
Platform: linux
Compiler: Not Provided


Hi,

This is related to how C++ new works and how C++ object works.

Unlike C, C++ objects have constructors. The constructor is called when initializing the object to setup required values for the object to operate properly. With new, it allocates the required memory and calls the constructor to setup the TString. But with malloc it just allocate memory and does not initialize the object; leaving an empty shell of the object behind. When you use the empty shell - it crashes.

Thank you very much marty1885.
kind regards

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.