Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cstring function use problems 1

Status
Not open for further replies.

0x4B47

Programmer
Jun 22, 2003
60
US
Dear fellow coders,
I can't seem to understand why im getting tun-time problems with the following code snippet:

Code:
int main()
{
	char* s = 0;
        char fubar[] = { "fubar" };
	strcat( s, " fubar " ); // troublesome line
	strcpy( s, " fubar " ); // troublesome line
        strcat( s, fubar[] );   // troublesome line
        strcpy( s, fubar[] );   // troublesome line
	return 0;
}

Please guide me.
Thanks in advance.
Kunal.
 
s isn't pointing at any usable memory.
More specifically, you've set it to point at 0 (or NULL), which will always trap if you try and access it.

Code:
char *s = 0;   // nowhere yet

s = new char[100];  // now similar to s[100];

strcpy( s, "hello" );
strcat( s, fubar );

delete [] s;

--
 
Yeh but the reason i did that was because i understand that pointers have to be initialised when they are declared. Now your solution will work and its a good one, but what I was wondering is, whats the point of initialising a pointer to 0 (null) if you cant assign it something at run-time?
 
Just to add to that last comment,
I dont know how many chars i want char* to hold, therefore if i do, char[100], and only want to hold 3 chars then im wasting quite a bit of memory.
 
> whats the point of initialising a pointer to 0 (null) if you cant assign it something at run-time?
To trap errors in your code.

If you simply said
[tt]char *s;[/tt]

Then your code may randomly work or not work. Sometimes, it works for a very long time (like years) before not working.
Worse still, since you wrote over something you shouldn't have, its usually something else which doesn't work. These kind of memory corruption bugs are notoriously difficult to find even for experienced programmers.

[tt]char *s = 0;[/tt]
makes sure it doesn't work a lot sooner than you would think, giving you the chance to fix the problem. It is a specific "somewhere" which is always guaranteed (on supporting operating systems) to fail.

> I dont know how many chars i want char* to hold
Well 100 was an example, you can use anything you like, even a computed answer
Code:
int len = strlen( source );
char *s = new char[ len + 1 ];
strcpy( s, source );  // fits just nicely :)

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top