David Bowskill wrote:

I have this little problem with GCC which I wonder if anyone can enlighten me on. The little program below has been run on three different machines all with the same result. The program compiles OK under GCC but fails with a segmentation error. Under Borland 'C for DOS', it compiles and runs correctly.

The essential problem is that you are allocating a string of constant characters and then trying to alter them. Depending on the quality of memory protection on the host this might or might not succeed. Thus the difference between DOS and UNIX.

You can fix this by allocating non-constant memory
to hold the string.

I've re-written the code using more normal C idioms.
Note that it still has a bug -- the behaviour of
the character value 255.  You should really handle this
explicitly (with code or comment) so that maintainers
are not forced to guess if you intend this increment
to result in '\0' (with nasty premature termination
of string consequences) or to remain at 255.



#include <stdio.h>    /* For printf() */
#include <string.h>   /* For strdup() */
#include <stdlib.h>   /* For free() */

static char* string_inc(char *s) {
    char *p;

    for (p = s; *p != '\0'; p++) {
        (*p)++;
    }
    return s;
}


int main(void) { char *s;

    s = strdup("This is a test");
    printf("%s\n",
           string_inc(s));
    free(s);

    return 0;
}


-- Glen Turner Tel: (08) 8303 3936 or +61 8 8303 3936 Australia's Academic & Research Network www.aarnet.edu.au -- SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/ Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to