Thread: Concatenate ascii threads - segmentation fault

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    1

    Question Concatenate ascii threads - segmentation fault

    I have a hexadecimal string that I want to convert to a regular string (to send as a tcp message).

    I took every two digits (say 61), converted them to a long int (say my_int = 6*16 +1 = 97) and got the corresponding ascii character (in this case "a")
    Code:
    //e.g. 
    	char* string1 = (char*) 97;
    string1 points to the character string "a" whose ascii value is 97.

    Code:
    char* string1 = (char*) my_int;
    char* string2 = (char*) my_int2;
    
    char* string2 = malloc(1024);
    Now I want to concatinate string1 and string2, and store them in string2.
    But I get a segmentation fault, whether I use strcpy(), strcat(), or even a function that I write.

    (PS: I am writing in C and I need the final string to be of type char*)

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    You're declaring string2 twice and overwriting it's initial value. If there isn't a null character soon enough in the new allocated memory, you'll easily end up running out of bounds - hence the segfault. But even if there was - you're not concatenating what you think you're concatenating.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > string1 points to the character string "a" whose ascii value is 97.
    No, it points to address 97, which could be anything - even a segfault.

    Start with something like this
    Code:
    printf("Some chars = %c %c %c\n", 'a', 97, 0x61 );
    int foo = 97;
    char buff[1024];
    sprintf( buff, "Int=%d, char=%c\n", foo, foo );
    printf( "Buff=%s", buff );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lame null append cause buffer to crash
    By cmoo in forum C Programming
    Replies: 8
    Last Post: 12-29-2008, 03:27 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM

Tags for this Thread