473,408 Members | 1,876 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

get corruption at end of string

Hello

I am using ifstream to load the contents of a text file into a char*
variable. I am allocating using new with the file size as amount to
allocate. My problem is that the variable contains a load of misc
extraneous data at the end of the variable.

Here is the code.

int main(int argc, char* argv[])
{
std::ifstream myfile;
std::string line;
long begin,end;
char szFile[256];
char* memblock;
std::ifstream::pos_type size;
std::cout << "Enter filename to open: ";
std::cin.getline(szFile, 256);
std::cout << "You selected file: " << szFile << std::endl;
myfile.open( szFile );
if (myfile.is_open())
{
begin = myfile.tellg();
myfile.seekg (0, std::ios::end);
end = myfile.tellg();
size = end-begin;
memblock = new char [size];
myfile.seekg (0, std::ios::beg);
myfile.read (memblock, size);
myfile.close();

std::cout << memblock << std::endl;

delete [] memblock;
}

return 0;
}

if I myfile.read just size then why do I get all the unallocated characters
at the end of the memblock variable?

Angus
May 23 '07 #1
5 1909
"Angus" <no****@gmail.comwrote in
news:f3*******************@news.demon.co.uk:
Hello

I am using ifstream to load the contents of a text file into a char*
variable. I am allocating using new with the file size as amount to
allocate. My problem is that the variable contains a load of misc
extraneous data at the end of the variable.

Here is the code.

int main(int argc, char* argv[])
{
std::ifstream myfile;
std::string line;
long begin,end;
char szFile[256];
char* memblock;
std::ifstream::pos_type size;
std::cout << "Enter filename to open: ";
std::cin.getline(szFile, 256);
std::cout << "You selected file: " << szFile << std::endl;
myfile.open( szFile );
if (myfile.is_open())
{
begin = myfile.tellg();
myfile.seekg (0, std::ios::end);
end = myfile.tellg();
size = end-begin;
memblock = new char [size];
myfile.seekg (0, std::ios::beg);
myfile.read (memblock, size);
myfile.close();

std::cout << memblock << std::endl;

delete [] memblock;
}

return 0;
}

if I myfile.read just size then why do I get all the unallocated
characters at the end of the memblock variable?
Because you're reading into a C-style string. You have no terminating
nul ('\0') character at the end of your C-style string. Thus the cout
<< memblock stuff has no idea when to stop reading your string.

If you really want to stick with C-style strings, replace your "new" line
with:

memblock = new char[size + 1];
memblock[size] = '\0';

May 23 '07 #2
On May 23, 5:54 pm, "Angus" <nos...@gmail.comwrote:
I am using ifstream to load the contents of a text file into a char*
variable. I am allocating using new with the file size as amount to
allocate. My problem is that the variable contains a load of misc
extraneous data at the end of the variable.
Here is the code.
A meta-comment: this would be a lot easier and clearer if you'd
use std::string.
int main(int argc, char* argv[])
{
std::ifstream myfile;
std::string line;
long begin,end;
char szFile[256];
char* memblock;
I'd initialize this to something, at least NULL. Or just
define it later, when you can initialize it correctly.

In general, it is bad policy to define variables before you can
correctly initialize them. In the case of pointers, it's
particularly serious.
std::ifstream::pos_type size;
std::cout << "Enter filename to open: ";
std::cin.getline(szFile, 256);
std::cout << "You selected file: " << szFile << std::endl;
myfile.open( szFile );
if (myfile.is_open())
{
begin = myfile.tellg();
myfile.seekg (0, std::ios::end);
Note that this seek may set eofbit, which will in turn cause all
further operations to fail. (I don't think it's supposed to,
but I believe that it does, or at least did, in some
implementations. I'd throw in a call to clear(), here, just to
be sure.)
end = myfile.tellg();
size = end-begin;
Note that this is not guaranteed to give you anything
significant. In the case of Unix, it probably will result in
the file size. In the case of Windows, it will almost surely be
more than is necessary. And on other systems, it might have no
relationship what so ever to the real file size.
memblock = new char [size];
myfile.seekg (0, std::ios::beg);
myfile.read (memblock, size);
Did the read succeed? How many characters did you really read?

istream::read() is a funny function, since it can "fail" even
when it partially succeeds. Basically, it will "fail" unless it
can read size characters (which will almost certainly be the
case if you're not on Unix). Basically, you need to call
gcount(), to know how many characters it actually read---only if
gcount() returns 0 did the read completely fail.
myfile.close();
std::cout << memblock << std::endl;
Since memblock isn't '\0' terminated, it's not a legal argument
to << here.

Personally, I'd write this entire block:

std::istringstream s ;
s << myfile.rdbuf() ;
std::cout << s.str() << std::endl ;

If for some reason I really needed a C style array, and didn't
have to worry about portability beyond Unix and Windows, I'd do
something along the lines of:

// Calculate size as above. It will be exact
// under Unix, and >= the real size under Windows,
// typically a little greater, but not too much.
std::vector< char buffer( size + 1 ) ;
myfile.read( &buffer[ 0 ], size ) ;
size = myfile.gcount() ;
if ( ! myfile && size == 0 ) {
// Error...
} else {
buffer[ size ] = '\0' ;
// use &buffer[ 0 ] as C style string...
}
delete [] memblock;
}

return 0;
}
if I myfile.read just size then why do I get all the unallocated characters
at the end of the memblock variable?
Because you don't terminate the C style string. And because you
don't check how many characters you've actually read, to know
where to terminate it.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 24 '07 #3

"James Kanze" <ja*********@gmail.comwrote in message
news:11**********************@m36g2000hse.googlegr oups.com...
On May 23, 5:54 pm, "Angus" <nos...@gmail.comwrote:

Personally, I'd write this entire block:

std::istringstream s ;
s << myfile.rdbuf() ;

If I try that I get this compile error:
ifstreamtest.cpp(99) : error C2676: binary '<<' : 'class
std::basic_istringstream<char,struct std::char_traits<char>,class
std::allocator<char' does not define this operator or a conversion to a
type acceptable to the predefined operator

May 27 '07 #4
Angus wrote:
"James Kanze" <ja*********@gmail.comwrote in message
news:11**********************@m36g2000hse.googlegr oups.com...
On May 23, 5:54 pm, "Angus" <nos...@gmail.comwrote:

Personally, I'd write this entire block:

std::istringstream s ;
s << myfile.rdbuf() ;

If I try that I get this compile error:
ifstreamtest.cpp(99) : error C2676: binary '<<' : 'class
std::basic_istringstream<char,struct std::char_traits<char>,class
std::allocator<char' does not define this operator or a conversion to a
type acceptable to the predefined operator
I think James meant

std::ostringstream s ;
s << myfile.rdbuf() ;

john
May 27 '07 #5
On May 27, 11:57 pm, John Harrison <john_androni...@hotmail.com>
wrote:
Angus wrote:
"James Kanze" <james.ka...@gmail.comwrote in message
news:11**********************@m36g2000hse.googlegr oups.com...
On May 23, 5:54 pm, "Angus" <nos...@gmail.comwrote:
Personally, I'd write this entire block:
std::istringstream s ;
s << myfile.rdbuf() ;
If I try that I get this compile error:
ifstreamtest.cpp(99) : error C2676: binary '<<' : 'class
std::basic_istringstream<char,struct std::char_traits<char>,class
std::allocator<char' does not define this operator or a conversion to a
type acceptable to the predefined operator
I think James meant
std::ostringstream s ;
s << myfile.rdbuf() ;
Yes, obviously. If you're writing to a stream, it has to be an
ostream of some sort. Thanks for the correction.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 28 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Mike | last post by:
I have done a lot of research on DAO and database corruption and have not yet found any solid information for my problem. I use DAO extensively in my Access 97 databases (back-end on network,...
4
by: DFS | last post by:
" has detected corruption in this file. To try to repair the corruption, first make a backup copy of the file. Then, on the Tools menu, point to Database Utilities and click Compact and Repair...
47
by: ship | last post by:
Hi We need some advice: We are thinking of upgrading our Access database from Access 2000 to Access 2004. How stable is MS Office 2003? (particularly Access 2003). We are just a small...
4
by: indushekara | last post by:
Hi, We are having memory corruption in our application somewhere, unable to find out. one part of code we found that we are specifying wrong format specifier. Could anyone let me know if the...
8
by: ranjeet.gupta | last post by:
Dear All Is the Root Cause of the Memory corruption is the Memory leak, ?? suppose If in the code there is Memory leak, Do this may lead to the Memory Corruption while executing the program ? ...
1
by: Humber Consumer | last post by:
I have a simple question. I have following piece of code in a sample MFC application: void CSampleAppDlg::OnButton1() { try { char e; ...
14
by: Peter Schmitz | last post by:
Hi, I'm currently developing an application that includes an implementation of the well-known Boyer- Moore algorithm. For this, I use the implementation of Thierry Lecrq from...
23
by: Dave G | last post by:
Since upgrading one of my clients from A97/W2000 to A2003/XP they have suffered no end of data corruption problems, mainly involving one of the main tables. The corruption can result in one...
6
by: Active8 | last post by:
Hi: This prob "magically" stopped and I'm not sure if I can recreate it, but thought I'd share it and maybe learn something. #include "stdafx.h" #include <stdlib.h> #include <math.h>...
2
by: Bob Doe | last post by:
I've been told there is memory corruption for buf.str().c_str() Can someone explain why?: void myFunc() { std::stringstream buf; buf << "some string"; const char *data = buf.str().c_str(); ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.