Re: How can a string by accidently modified?



/*

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

.



Relevant Pages

  • Re: socket communication: send & receive doesnt work right
    ... So I don't want to send a string as bytes. ... public void send_doubles(double vals, int len) throws ... // send a short acknowledgement to the server ... char *result; ...
    (microsoft.public.win32.programmer.networks)
  • Re: [PATCH] markers: modpost
    ... pointers to the name/format string pairs. ... The same can then be done with modules using the __markers section. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: [PATCH] markers: modpost
    ... This adds some new magic in the MODPOST phase for CONFIG_MARKERS. ... will be a neighbor of its format string. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: Is this code totaly a shit?
    ... | void UppStrg(char *Low, char *Upp, int cnt); ... whitespace-delimited string. ... You're also assuming that the representations of the characters ...
    (comp.lang.c)
  • Re: A string collection abstract data type
    ... duplicate string in Insert, InsertAt, ReplaceAt; ... used int instead of size_t for count and size for consistency with API. ... char *(StringCollection *SC, int idx, ... static int IsReadOnly; ...
    (comp.lang.c)