-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
My program crashes on the following code,
void lower(char* src, char* ret){
while ( src ) {
char c = tolower(*src);
*ret = c; <----------------------------- crash here
++ret;
++src;
}
return;
}
the calling of this function is like this,
char* s1 = "aBcDeFg";
char* s2 = "1234567";
lower(s1, s2);
Do you see what is wrong?
Yes
1) Your loop will terminate when src equals (char *)0 (the NULL pointer). You
don't want this; you want the loop to terminate when *src equals \0
2) If indeed you are calling your lower() function with the s1 and s2 you
presented, then you are doing it wrong. As s2 is a pointer to a fixed string
(/what/ does the standard call that?), alteration of the characters in that
string invokes (IIRC) undefined behaviour. Your operating system /may/ cause
the program to abend with the equivalent of a "trying to alter unalterable
memory" error. Instead, you want to call lower() with ret pointing to
alterable memory, something like...
{
void lower(char *, char *);
char *s1 = "This is a string", /* unalterable */
s2[60]; /* alterable */
lower(s1,s2);
}
3) In lower(), you don't length check the space pointed to by the ret
argument. What would happen if you called lower() with a ret that points to a
smaller area than the src points to? As in...
{
void lower(char *, char *);
char s1[] = "This is a long string",
s2[] = "Short";
lower(s1,s2);
}
HTH
- --
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
- ---------- Slackware - Because I know what I'm doing. ------
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Armoured with GnuPG
iD8DBQFGX2WTagVFX4UWr64RAl4BAKCAwV+6kG6gOzkrt15dg6H4FVGbFACeJ/LL
/LUp15tkEqcp41XPHAof9+U=
=3L12
-----END PGP SIGNATURE-----