crashing code

This is a discussion on crashing code within the C Programming forums, part of the General Programming Boards category; Why doesn't this code work? Is it because I have to allocate memory for char* tool_tip_text and how would I ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    380

    crashing code

    Why doesn't this code work? Is it because I have to allocate memory for char* tool_tip_text and how would I do that?

    I've tried allocating memory using this, but it doesn't help either.
    button->tool_tip_text = malloc(sizeof(char) * strlen(text)+1)

    Code:
    typedef struct {
       char* tool_tip_text;
    }BUTTON;
    
    int create_button(BUTTON* button, char* text)
    {
       printf("%d",strlen(text));
       strcpy(button->tool_tip_text,text);
       return 0;
    }
    
    create_button(&my_button[0],"New Level");
    Don't you dare hit me on the head, you know I'm not normal.
    A Stooge Site
    Green Frog Software

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    380
    After including the proper header file that code does actually fixes this problem.

    I have one more question. Why doesn't this error checking work, unless I merge these two lines?

    button->tool_tip_text = malloc(sizeof(char) * (strlen(text)+1) );
    if(button->tool_tip_text == NULL)
    return -1;
    Don't you dare hit me on the head, you know I'm not normal.
    A Stooge Site
    Green Frog Software

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    380
    button->tool_tip_text = malloc(sizeof(char) * (strlen(text)+1) );
    if(button->tool_tip_text == NULL)
    return -1;

    if((button->tool_tip_text = malloc(sizeof(char) * strlen(text)+1)) == NULL)
    return -1;

    Out these two samples of code the second one does what I want it to do. Why couldn't first line of code work?
    Don't you dare hit me on the head, you know I'm not normal.
    A Stooge Site
    Green Frog Software

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 08:23 AM
  2. Explain this C code in english
    By soadlink in forum C Programming
    Replies: 16
    Last Post: 08-31-2006, 01:48 AM
  3. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 06:06 PM
  5. Replies: 4
    Last Post: 01-16-2002, 12:04 AM

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