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

run time Error :(

hello all have been trying to write a Mid() function a bit like the one in
vb. i come to compile it and there are no errors however when i run it an
error accours and it says the program has to close. The odd thing is the
error accours after the mid function has done its job. but if i take out the
mid function the error does not accour.

i have found that if i do

cout <<mid(newString.GetString(),iPosition,3);

the erorr will occur. However if i do

cout <<strcpy(new char,mid(newString.GetString(),iPosition,3));

the erorr does not occur.

If i debug it . . im given the error message "Unhandled exception in
Main.exe: 0xc0000005: Access Violation." and it takes me to the part that
its says the error occurs.

The following If statment is where it says it is going wrong (i did not
write this code it must be part of the code that comes with c++)

if (!CheckBytes(pbData(pHead) + pHead->nDataSize,
_bNoMansLandFill, nNoMansLandSize))
_RPT3(_CRT_ERROR, "DAMAGE: after %hs block (#%d) at
0x%08X.\n",
szBlockUseName[_BLOCK_TYPE(pHead->nBlockUse)],
pHead->lRequest,
(BYTE *) pbData(pHead));
The following code is my mid function code that i wrote (it all compiles
with out any errors).
char* mid(char* cStringBeingSentIn, int iPositionToStartAt, int iLength)
{
iLength = iLength - 1;

char *cNewStringBeingLookedAt = (char*)malloc(iLength+1+1);
int iCharPositionToBeStoredAt = 0;
if ((iPositionToStartAt + iLength+1) > (int)strlen(cStringBeingSentIn) )
{
return new char = "ERROR";
}

if (cStringBeingSentIn == NULL)
{
return new char = "ERROR";
}

if ( (iPositionToStartAt <0) || (iLength < 0) )
{
return new char = "ERROR";
}

if (strlen(cStringBeingSentIn) == 0)
{
return new char = "ERROR";
}

for (int iCount = iPositionToStartAt; iCount <= iPositionToStartAt +
iLength; iCount++)
{
cNewStringBeingLookedAt[iCharPositionToBeStoredAt] =
cStringBeingSentIn[iCount];
iCharPositionToBeStoredAt++;
}

cNewStringBeingLookedAt[iLength+1] = '\0';

return strcpy(new char,cNewStringBeingLookedAt) ;
}
Any help would be grate if any one can figure out what going on. Thanks in
adv.

Gizmo.


Jul 19 '05 #1
3 4323
Gizmo wrote:
hello all have been trying to write a Mid() function a bit like the one in
vb.


First question: Why? What's wrong with std::string function substr()
which does exactly the same.

string substr (size_type pos, size_type n);
Returns a substring of the current string, starting at position pos and
of length n:

Example:
------------------------------------------------------
#include <iostream>
#include <string>
int main()
{
std::string str18 = "abcdefghi";
std::string str19 = str18.substr(6,2);
std::cout << str19 << std::endl; // Prints out: "gh"
return 0;
}
------------------------------------------------------

Jul 19 '05 #2

"Gizmo" <sc***********@hotmail.com> wrote in message
news:bi**********@news6.svr.pol.co.uk...
hello all have been trying to write a Mid() function a bit like the one in
vb. i come to compile it and there are no errors however when i run it an
error accours and it says the program has to close. The odd thing is the
error accours after the mid function has done its job. but if i take out the mid function the error does not accour.
[snip]
Any help would be grate if any one can figure out what going on. Thanks in
adv.

Gizmo.

There quite a lot wrong with the posted code. I think you need to pick up
your favourite C++ book and have a look at dynamic memory allocation and
string handling.
return new char = "ERROR"; return strcpy(new char,cNewStringBeingLookedAt) ;


These two lines are completely bogus. I'd like to offer some advice but I
can't really see what you think you are doing here. Here's how you should
allocate memory for a string

char* aString = new char[aLength + 1];

Hope this helps.

john
Jul 19 '05 #3
Gizmo wrote:
hello all have been trying to write a Mid() function a bit like the one in
vb.
That doesn't help me. What is Mid() supposed to do?
i come to compile it and there are no errors however when i run it an
error accours and it says the program has to close. The odd thing is the
error accours after the mid function has done its job. but if i take out the
mid function the error does not accour.

i have found that if i do

cout <<mid(newString.GetString(),iPosition,3);
What is newString? It looks like some non-standard string class. Why are
you not using the standard class std::string?

the erorr will occur. However if i do

cout <<strcpy(new char,mid(newString.GetString(),iPosition,3));
This is doomed to fail. If mid returns a pointer to a string longer than
0 characters you will write over memory you don't own. 'new char' gives
you *one* char. Just one. Try to copy more than that and your program
will go down in flames, or worse.

Part of the problem here is that you are using char pointers as C-style
strings. You would be much better off using std::string.

the erorr does not occur.

If i debug it . . im given the error message "Unhandled exception in
Main.exe: 0xc0000005: Access Violation." and it takes me to the part that
its says the error occurs.

The following If statment is where it says it is going wrong (i did not
write this code it must be part of the code that comes with c++)
'C++' does not come with code. This is part of a particular C++
implementation. It looks like MS Visual C++ to me.

The error indicates that you've written to memory you don't own. The
code below indicates that you've written past the end (or before the
beginning) of a dynamically allocated chunk of memory. Incidentally,
this is exactly what is likely to happen with your 'strcpy(new char' above.

if (!CheckBytes(pbData(pHead) + pHead->nDataSize,
_bNoMansLandFill, nNoMansLandSize))
_RPT3(_CRT_ERROR, "DAMAGE: after %hs block (#%d) at
0x%08X.\n",
szBlockUseName[_BLOCK_TYPE(pHead->nBlockUse)],
pHead->lRequest,
(BYTE *) pbData(pHead));
The following code is my mid function code that i wrote (it all compiles
with out any errors).
That certainly does not mean it's correct.


char* mid(char* cStringBeingSentIn, int iPositionToStartAt, int iLength)
{
iLength = iLength - 1;

char *cNewStringBeingLookedAt = (char*)malloc(iLength+1+1);
Don't use malloc unless you have a very good reason. You don't seem to
have any reason in this case. Use 'new' instead.
int iCharPositionToBeStoredAt = 0;
if ((iPositionToStartAt + iLength+1) > (int)strlen(cStringBeingSentIn) )
This cast is a bad idea. First, don't use C-style casts in C++. Use a
C++ cast operator instead (static_cast in this case). Second, converting
size_t to int may have unexpected results. You'd do better to convert
the left side to size_t, or to write code that doesn't require casts.
{
return new char = "ERROR";
This is so wrong I hardly know where to start. 'new char' returns a
pointer to one, single, solitary character. That single character cannot
store an entire string, only a single character. Even if you allocated
enough space for your entire "ERROR" string, the assignment is
completely wrong. All you are doing is allocating a char, then
immediately assigning the address of a string literal to the temporary
char * that was pointing to your allocated char (which causes a memory
leak since you no longer have a pointer to your allocated char), then
returning that address. The effect is the same as this:

new char;
return "ERROR";

Any attempt outside this function to modify the string that was returned
or to delete it will break your program. You can't modify a string
literal, so it's a very bad idea to ever create a (non-const) pointer to
one. In fact, conversion from string literal to (non-const) char* is a
deprecated language feature.

Besides that, if you return here you leak the memory pointed to by
cNewStringBeingLookedAt.
}

if (cStringBeingSentIn == NULL)
{
return new char = "ERROR";
Same problem.
}

if ( (iPositionToStartAt <0) || (iLength < 0) )
{
return new char = "ERROR";
And again.
}

if (strlen(cStringBeingSentIn) == 0)
{
return new char = "ERROR";
And again.
}

for (int iCount = iPositionToStartAt; iCount <= iPositionToStartAt +
iLength; iCount++)
{
cNewStringBeingLookedAt[iCharPositionToBeStoredAt] =
cStringBeingSentIn[iCount];
iCharPositionToBeStoredAt++;
}

cNewStringBeingLookedAt[iLength+1] = '\0';
I don't understand what any of this is intended to do, but it looks very
dangerous.

return strcpy(new char,cNewStringBeingLookedAt) ;
This is extremely broken. Again, you are returning without freeing the
memory pointed to by cNewStringBeingLookedAt. But even worse is that you
are again trying to copy a string into a single char.
}
Any help would be grate if any one can figure out what going on. Thanks in
adv.


What's going on is that you seem to have very little understanding of
pointers, strings, or dynamic memory. You need to back up and learn
these things before you attempt to use them in anything non-trivial.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #4

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

Similar topics

18
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion...
5
by: Carmine Cairo | last post by:
Hi, I'm working on a project and today I've note a little problem during the compile fase. Here a little piece of code: // 1st version welldone = 0; size = p->getSize(); backbone = new...
4
by: Christaaay | last post by:
I have been using the code below successfully for almost a year. yesterday, I began getting a run time error 6 (overflow). I am using the code in an Access 2000 database. Can anyone help me...
1
by: MLH | last post by:
I want to change my system time date each time an A97 app is started. Here's how I've been doing it. Am looking for a better way. Sure some of you have researched this. Function...
1
by: Mark | last post by:
I have .aspx code-behinds that inherit from the class below. The code runs just fine, but the form designer bombs at design time when trying to view the .aspx page in VS.NET 2003. If I comment...
1
by: Alfonso Morra | last post by:
Hi I'm compiling some code and need to generate some random numbers. To save time, I decided to use the srand, rand and time functions. My code worked (atleast built fine) until I added time.h,...
4
by: HNguyen | last post by:
Hi, I have a Web application in ASP.NET. My Application allows the users upload files into the server after checking their user names and passwords. For each transaction, the Web program will...
15
by: Khurram | last post by:
I have a problem while inserting time value in the datetime Field. I want to Insert only time value in this format (08:15:39) into the SQL Date time Field. I tried to many ways, I can extract...
9
by: ThunderMusic | last post by:
Hi, I'd like to create a compile time error in my class... maybe there's a way already built in in the framework so I can achieve what I want... I have 2 constructors in my class. One of them...
4
by: ahmurad | last post by:
Dear Xperts, In my database table some fault code type records are inserted and the values are like bellows: Error:2/FC:10; 00:15:13 16/03/2009; Error:2/FC:20; 00:15:15 16/03/2009; ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.