[Search for users] [Overall Top Noters] [List of all Conferences] [Download this site]

Conference turris::c_plus_plus

Title:C++
Notice:Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS)
Moderator:DECCXX::AMARTIN
Created:Fri Nov 06 1987
Last Modified:Thu Jun 05 1997
Last Successful Update:Fri Jun 06 1997
Number of topics:3604
Total number of notes:18242

3409.0. "Still problem with >> String class insertion oper" by TAV02::MILCHIN () Thu Jan 23 1997 08:35

T.RTitleUserPersonal
Name
DateLines
3409.1HNDYMN::MCCARTHYA Quinn Martin ProductionThu Jan 23 1997 09:043
3409.2memory corruptionHNDYMN::MCCARTHYA Quinn Martin ProductionThu Jan 23 1997 10:474
3409.3SOMETHING NEW???TAV02::MILCHINMon Feb 10 1997 06:1510
	HI!

	I would like to know if there is any progress in checking of String
class insertion operator (>>) memory leak problem, as described in .0?
I also verified that the problem exists on OPENVMS ALPHA V7.1.

	REGARDS!
		MICHAEL

	P.S.: Is IPMT report for this case preferable?
3409.4not a memory leak, a memory corruptorHNDYMN::MCCARTHYA Quinn Martin ProductionMon Feb 10 1997 08:537
>>class insertion operator (>>) memory leak problem, as described in .0?

It is not a memory leak.  The code allocates a buffer of 1024 on the stack 
and then calls a lower level routine to put the input into.  So, when 1024 is
read in, then the \0 is added - memory corruption.

bjm
3409.5work arounds for code - recommend #2HNDYMN::MCCARTHYA Quinn Martin ProductionMon Feb 10 1997 16:1160
We can think of two possible workarounds.

Solution 1 - using existing String class:
/*
If you know your buffer length is going to
be greater than 1024 chars, use operator>>(const char*) 
to read the string into a char buffer and then copy that 
buffer into the string, i.e.:
*/
#include <fstream.hxx>
#include <string.hxx>
#include <stdlib.h>

const int MAX_LINE_LENGTH = 4028; // set this to your maximum record length

main()
{
  String token1;

  ifstream s("test_ifstream.dat");

  if (!s) { cerr << "test_ifstream.dat is not found\n"; exit(1); }

  while(!s.eof()) {
    char buf[MAX_LINE_LENGTH];
    s >> buf;
    token1 = buf;
    cout << token1.length() << endl;
    cout << token1 << endl;
  }
}

Solution 2 - using new ANSI string class:
/*
Use the new ANSI standard string class. This is available
with DEC C++ V5.5 or later. See Using Guide for hints on 
to upgrade from the non-ANSI string class. In your simple 
example, all you would have to is change String to string 
and compile:
$ CXX/ASSUME=NOHEAD PROG.CXX 
$ CXXLINK prog
*/

#include <fstream.h>
#include <string>

main()
{
  string token1; // this is the ANSI string class

  ifstream s("test_ifstream.dat");

  if (!s) { cerr << "test_ifstream.dat is not found\n"; exit(1); }

  while(!s.eof()) {
    s >> token1;
    cerr << token1.length() << '\n';
    cerr << token1 << '\n';
  }
}