Re: How can a string by accidently modified?
- From: "lovecreatesbeauty" <lovecreatesbeauty@xxxxxxxxx>
- Date: 15 Jan 2006 23:13:46 -0800
/*
modify a (constant) character string is an undefined behavior. see:
`K&R C, 2nd', §5.5,
`H&S C: A reference manual, 5th', §2.7.4
*/
#include <stdio.h>
#include <string.h>
void manip(char *s)
{
if (s != NULL && strlen(s) >= 2)
{
s[0] = 'A';
s[1] = 'B';
}
}
int main(int argc, char *argv[])
{
char *s = "hello";
printf("argv: %s\n", argv[1]);
printf("constant character string: %s\n", s);
printf("--- --- ---\n");
/* works on both Win32 and HP-UX for this argv[1]*/
manip(argv[1]); /* line */
printf("argv modified: %s\n", argv[1]);
/* runtime error on Win32 but works on hp-ux 11 for this compiling
time constant string */
manip(s); /* line */
printf("constant character string modified: %s\n", s);
return 0;
}
Chad wrote:
> Given the following code that achieves no useful purpose:
>
> #include <string.h>
> #include <stdio.h>
> #include <string.h>
>
> int manip(char *str) {
>
> size_t len = strlen(str)-1;
> if(len >= 3) {
> str[0] = 'A';
> str[1] = 'B';
> printf("The length of the string is: %d\n", len);
> }
> else {
> return -1;
> }
> }
>
> int main(int argc, char **argv){
>
> if(argc !=2){
> fprintf(stderr,"Not enough arguements\n");
> exit(1);
> }
>
> manip(argv[1]);
> printf("The modified value is: %s\n",argv[1]);
>
> argv[1] = NULL;
> printf("The new modified value is: %s\n",argv[1]);
>
> return 0;
> }
>
> I really don't know how to word this in any graceful way. Please bear
> with this. How is it possible to accidently modify the string in
> argv[1]? I can maybe see something like malloc() returning NULL, then
> maybe like having this value be passed to manip(), but other than that,
> really see this.
>
> Thanks in advance
> Chad
.
- Follow-Ups:
- Re: How can a string by accidently modified?
- From: lovecreatesbeauty
- Re: How can a string by accidently modified?
- References:
- How can a string by accidently modified?
- From: Chad
- How can a string by accidently modified?
- Prev by Date: fgets
- Next by Date: Re: some problem of a.out
- Previous by thread: Re: How can a string by accidently modified?
- Next by thread: Re: How can a string by accidently modified?
- Index(es):
Relevant Pages
|