anything wrong with this code?

This is a discussion on anything wrong with this code? within the C Programming forums, part of the General Programming Boards category; it's been compiled successfully. but "segmentation fault" always if run it. -------------------------------------------- #include <stdio.h> void mystrcat(char *, char *); main() ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    64

    anything wrong with this code?

    it's been compiled successfully. but "segmentation fault" always if run it.

    --------------------------------------------
    #include <stdio.h>

    void mystrcat(char *, char *);

    main() {
    char *s = "Hello ";
    char *t = "World!";
    mystrcat(s, t);
    printf("%s\n", s);
    }

    void mystrcat(char *s, char *t) {
    while ( *s++ = *t++ )
    ;
    }


    -------------------------------------------------

  2. #2
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    since

    char *s = "Hello ";
    char *t = "World!";

    only allocates 7 bytes for each string, trying to append more bytes to the end of those strings would cause a runtime error.

    char s[200] = "Hello ";
    char t[] = "World!";

    would allocate enough space in s to allow for loads more characters to be added on.

    Also,

    while ( *s++ = *t++ )
    ;

    simply overwrites s with t.

    try
    Code:
    void mystrcat(char *s, char *t) 
    {
        while ( *++s != '\0');
        while ( *s++ = *t++ != '\0');
    }
    finally, use int main(void), or int main (int, char **) rather than main().

    Code:
    #include <stdio.h>
    
    void mystrcat(char *s, char *t);
    
    int main(void) 
    {
        char s[100] = "Hello ";
        char t[] = "World!";
        mystrcat(s, t);
        printf("%s\n", s);
        return 0;
    }
    
    void mystrcat(char *s, char *t) 
    {
        while ( *++s != '\0');
        while ( *s++ = *t++ != '\0');
    }
    here is your finished code, still not the best way of doing it though.

  3. #3
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    here is a decent tut on string handling in C

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    You may want to try:
    Code:
    char *s = (char*)malloc((int)255);
    strcpy(*s, "Hello");
    to create some extra space so you can put more characters in there.

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    64
    Yes, when I replace *s with s[], it work properly.

    I'm wondering why there's no boundary indeed for an array, to which we have even designate a number of size limit.

    e.g.,

    char s[100] = "Hello ";

    it still works even if 100 is omitted. and seems the string could be appended to any desired longer. like this:

    char s[] = "Hello ";
    Last edited by thinhare; 12-18-2004 at 07:40 PM.

  6. #6
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    Code:
    char array[]="Hello";
    assignes only Hello and a NULL character; it just does the counting for you ex same as
    Code:
    char array[6]="Hello";
    If you make it more say
    Code:
    char array[200]="Hello";
    then everything else is just extra room

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> Yes, when I replace *s with s[], it work properly.

    that's because string literals cannot be modified. their contents reside in read-only memory.

    >> it still works even if 100 is omitted

    no, you can legally access the first 6 elements of the array, period - after that you're playing with fire.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  8. #8
    Registered User
    Join Date
    Dec 2004
    Posts
    64
    >> it still works even if 100 is omitted

    no, you can legally access the first 6 elements of the array, period - after that you're playing with fire.[/QUOTE]

    I do realize that in this way, there could be some contents outside the array being overwritten unintendedly.

    But it's interesting that even C built-in "strcpy" doesn't do anything to check the bound of the array. that might just be that so-called flexibility.

  9. #9
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Quote Originally Posted by thinhare
    But it's interesting that even C built-in "strcpy" doesn't do anything to check the bound of the array. that might just be that so-called flexibility.
    The C language won't baby you. It assumes that you know what your doing, so if your gonna code in it - know what you're doing. . if you want to add up certain elements to a char array then use strncat.

    otherwise use some work around like finding out the length of your string using strlen and then adjusting accrodingly. Just remember if you use and array make sure you know its bounds.

    assignes only Hello and a NULL character; it just does the counting for you ex same as
    I'm assuming the use of capitals in "null" is to emphasis it. Othewise don't forget NULL and '\0' are two dif things. NULL - the NULL pointer is an address and the null character '\0' is char type object with the equivalent value zero. they could both be represented with the number '0' but they differ "conceptually" from each other.


    [edit]some more quest about strings that might be useful here [/edit]
    Last edited by caroundw5h; 12-18-2004 at 09:30 PM.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  10. #10
    Registered User
    Join Date
    Dec 2004
    Posts
    12

    precautions while handling strings!


    Hi all!
    I am a new entrant in this exciting communication channel.
    What i have observed is that u should always check for proper string lengths (both before and after the operation) at all the ends while handling strings.
    If u use pointers, make sure u have allocated enough memory before using them.
    All the best!
    Last edited by just_A_student; 12-20-2004 at 01:47 AM.

  11. #11
    not-a-geek
    Join Date
    Apr 2004
    Posts
    210
    Quote Originally Posted by Kleid-0
    You may want to try:
    Code:
    char *s = (char*)malloc((int)255);
    strcpy(*s, "Hello");
    to create some extra space so you can put more characters in there.
    You shouldn't cast malloc. If its' header is properly included, it returns a void pointer (which you don't have to cast) [thx Prelude]. Casting the integer "255" to int isn't neccessary either.

    And of course it should be
    Code:
    strcpy(s, "Hello");
    . You wouldn't want to copy it to the location represented by the first 4 (on most 32 bit systems) bytes of your uninitialized memory.
    main() { int O[!0<<~-!0]; (!0<<!0)[O]+= ~0 +~(!0|!0<<!0); printf("a function calling "); }

  12. #12
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    And when you use malloc, be sure to check that there is actually some memory allocated. With malloc, you are requesting some memory, but if there is not enough memory available, you will not get any. So be sure to include error checking.

  13. #13
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    You shouldn't cast malloc.
    unless you're attempting to make your C program C++ compatible. the casting is redundant in C, a necessity in C++.
    Code:
    char *p = malloc (10 * sizeof(char)  );
             if (p == NULL){
           perror("malloc");
           return 1;
    }
    a little implicit, but i'm sure you understand.


    [edit]changed after salem's chastising[/edit]
    Last edited by caroundw5h; 12-20-2004 at 10:43 AM.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,825
    > unless you're attempting to make your C program C++ compatible.
    Why would anyone want to do that?
    Unless you're into the bizarre world of writing polyglots, attempting such a thing is merely a diversion away from all the other issues.

    > if( (char *p = malloc (10 * sizeof(char) ) ) == NULL){
    I wonder what the scope of p is in this piece of code?

  15. #15
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Why would anyone want to do that?
    Unless you're into the bizarre world of writing polyglots, attempting such a thing is merely a diversion away from all the other issues.
    I'm sure polyglots are interesting in themselves and still another avenue for programmers to mix c and C++ code. Please dont' pretend like it doesn't happen salem. its actully so common there is a language called C/C++ , but you knew that already.
    > if( (char *p = malloc (10 * sizeof(char) ) ) == NULL){
    I wonder what the scope of p is in this piece of code?
    [talking *ish]
    its new, coming out in the new 2008 standard. its called declaration/definition scope. Kinda like function scope[/ralking *ish]
    truthfully, i had no idea you couldn't use malloc in a compund statement.

    edited.
    Last edited by caroundw5h; 12-20-2004 at 11:24 AM.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 08:10 AM
  2. what is wrong with this code please
    By korbitz in forum Windows Programming
    Replies: 3
    Last Post: 03-05-2004, 10:11 AM
  3. I cant find what is wrong with this code
    By senegene in forum C Programming
    Replies: 1
    Last Post: 11-12-2002, 06:32 PM
  4. Anyone see what is wrong with this code?
    By Wise1 in forum C Programming
    Replies: 2
    Last Post: 02-13-2002, 02:01 PM
  5. very simple code, please check to see whats wrong
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-10-2001, 01:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21