473,385 Members | 1,769 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,385 software developers and data experts.

C++ (char *) initialization issues

I've been trying to ignore this issue for a while now, but I've come to the point in my code where I can't do so anymore. (For those of you who are wondering, this is NOT a homework question).

Platform: VC++ 2002
System: Windows XP, sp3

::First, here's the code in question::

Expand|Select|Wrap|Line Numbers
  1. char * cSection (const char* data, int start, int finish)
  2. {
  3. if (start >= 0 && finish >= 0 && data != 0 && start < finish)
  4.     {
  5.     //allow for the null-terminator at the end of the
  6.     int ssLen = finish - start + 1 ;
  7.  
  8.     char * sect = new char[ssLen] ;
  9.  
  10.     for (int i = start ; i <= finish ; i++)
  11.         {
  12.         sect[i-start] = data[i] ;
  13.         }
  14.     return sect ;
  15.     }
  16.     return "Failed!" ;
  17. }
  18.  

::My understanding of the code, i.e. What Should Happen::
The code, as I understand and have written it, should create a character array of a size (minimum 1) equal to (finish - start) and should enter a number of characters from data into the resulting array.

::Notes::
Assume that data is a character array, and that start and finish are indexes in that array. The bounds checking takes place elsewhere in the program and so is not handled here.

::Problem, i.e. What Actually Happens::
The array gets created, with nearly 15 extra slots . Not only does it have those extra elements, but they are (naturally) filled with garbage that stays with the array until it gets deleted. This does get annoying as I am trying to parse information from the lines and the garbage is corrupting the data.

::What I have done so far::
I looked in the documentation, both online and on my computer, and nothing mentioned the extra character elements.

I googled some phrases:
-->"char initialization problems"
-->"initializing character array to wrong size"
-->"initializing character array to wrong length"
-->"variable length char array initialization"
-->"initializing character array C++ but incorrect number elements"
-->"initializing character array C++"

But I didn't find anything mentioning why I would get the extra elements in the array. I've never run into anything like this before in my programming career.

I guess I have two questions. Why this is happening? How can I fix this?
Nov 15 '08 #1
5 9833
newb16
687 512MB
You forgot to place terminating null in result string.
PS - you do some checks before actually copying data, but do not check whether start and finish actually belong to source string, ie do not exceed its length.
Nov 15 '08 #2
oler1s
671 Expert 512MB
Some things that I noticed as soon as I saw the code. If you want start and finish to be non-negative, make them unsigned int, and problem solved. ssLen needs to be finish-start +1 +1. There is a +1 for the null terminator. But there is also a +1 for finish-start. Let’s say finish is 3 and start is 1. Finish-start is 2. What you probably want is an array that is 1,2,3,\0, not 1,2,\0. Right? (Think of fenceposts. You want the posts, not the spaces in between.)

Now, you claim that the array gets 15 extra slots despite the code you wrote. Actually, I don’t see compilable code that demonstrates the issue. As in, I plop in the code to a compiler, and when I run it, I see the obvious result. I mention this because I have no idea how you determined the size of your array. You check ssLen in a debugger right before sect and then check the size of sect also in debugger right after it is created? I certainly hope you didn’t use strlen.
Nov 15 '08 #3
Hmmm. I had read something about 'null-terminated,' but hadn't made the connection. I'll add that to my code and see what happens.

@oler1s: I actually did use strlen because I didn't want to actually count the number of characters that showed up. I first noticed the problem when I output the character sequence to the command prompt and got a bunch of garbage on the end of what I expected.

As an additional note, the IDE I use also showed the additional characters when I examined the data in the watch window.

Hopefully, however, adding the null to the end of the character string will fix the problem.

Thank you both for your insight.

-codeGhost
Nov 16 '08 #4
Alright! Fixed!

The answer was the null-terminator at the end. It turns out that when I created the char * pointer, the program was assigning garbage from the heap?, or from somewhere, and continued assigning garbage until it ran into its own '\0.' In any case, assigning a null pointer to the end of the char * fixed the problem!

In short: If you're getting a character pointer array that is longer than you expect it to be, and the additional elements are just garbage, assign a null terminator('\0') to/beyond the end of the data you want to keep to fix the problem.

Again, thanks guys for your help!

-codeGhost
Nov 17 '08 #5
newb16
687 512MB
Alright! Fixed!

The answer was the null-terminator at the end. It turns out that when I created the char * pointer, the program was assigning garbage from the heap?, or from somewhere, and continued assigning garbage until it ran into its own '\0.' In any case, assigning a null pointer to the end of the char * fixed the problem!
Array allocated is 15 chars, but function you used to inspect it ( printf? ) do not know about its allocated size, it goes forward by memory until it get null char or access violation exception occurs. In your case, there was a null char somewhere near.
Nov 17 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
20
by: Petter Reinholdtsen | last post by:
Is the code fragment 'char a = ("a");' valid ANSI C? The problematic part is '("a")'. I am sure 'char a = "a";' is valid ANSI C, but I am more unsure if it is allowed to place () around the...
64
by: ng5000 | last post by:
Hi, What's the point of a signed char? As I see it a char represents a character (not an integer, use an int type e.g. short int if you want an 8 bit number, or one of the new types, uint8 I...
22
by: juanitofoo | last post by:
Hello, I've just switched to gcc 4 and I came across a bunch of warnings that I can't fix. Example: #include <stdio.h> int main() { signed char *p = "Hola";
33
by: Jordan Tiona | last post by:
How can I make one of these? I'm trying to get my program to store a string into a variable, but it only stores one line. -- "No eye has seen, no ear has heard, no mind can conceive what God...
17
by: Chad | last post by:
I'm want static char *output; to hold the modified string "tel chad" However, when I debug it, static char *output holds the ascii value of the strng, and not the string itself. Here is...
6
by: tropos | last post by:
For my sins, I'm maintaining some old C code which is migrated to C++. Dozens of lines of it looks like this: char *cfd_THE_ts_result_sql= "select TRADE_DATE , VALUE , " " from (" " select...
14
by: mdh | last post by:
And I thought I understood it, finally. Alas. given: char *s={"Jan","Feb","Mar","April"}; is it possible to have char *p point at s? *p = s...does not do it, as I expect. *p=s...I...
3
by: Arepi | last post by:
Hi, The following class decide which type is in the current instance and itialize depends on this information. The problem: When make an instance with any pointer type, a compilation error...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...

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.