Thread: Help Working with a char*

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    35

    Help Working with a char*

    I have a function that returns a char*. No problem. But I need to concatenate another array with the results of this function. I'm getting a segmentation error.

    What am I doing wrong? Thanks.

    Code:
    //this next line outputs correctly so I know my function is working
    fprintf(stdout, "%s\n", get_filename(selection));
    
    char* temp;
    
    //but this next line causes a segmentation fault
    strncpy(temp, get_filename(selection), sizeof(get_filename));
    
    //never runs
    fprintf(stdout, "here");
    my function if interested

    Code:
    char* get_filename(char selection[]) {
        
        char* end;
        char* start = strchr(selection,'[');
        
        if(start == NULL) {
            return NULL;
        }
        
        start ++;
        
        end = strchr(start ,']');
        
        if (end == NULL) {
            return NULL;
        }
        
        *end = 0;
        return start;
        
    }

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by joatmon View Post
    I have a function that returns a char*. No problem. But I need to concatenate another array with the results of this function. I'm getting a segmentation error.

    What am I doing wrong? Thanks.

    Code:
    char* temp;
    //but this next line causes a segmentation fault
    strncpy(temp, get_filename(selection), sizeof(get_filename));
    In the first line, you create a variable called temp which stores an address (of a character / of the first of a sequence of characters). Temp starts out, like most other variables, with random contents - it has a random memory address.

    Now, your next line of code tries to write to that random area of memory, without knowing what is there or even if that address is valid.

    You need another line where you actually allocate memory to hold the result of strncpy, and store the address of that memory in temp. Since you allocate this memory, at some point when you're done with it, you need to free it.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    I don't think you really don't need to copy the string to another location. You could just do:
    Code:
    char *filename = get_filename(selection);
    This depends on other details of your program, but it might be what you're looking for.

    Oh, and the last parameter of strncpy is wrong. You're passing in the size of a function ponter, not the size of the string!

    To do it safely, say with dynamic allocation (in case that's what you need) :
    Code:
    char *temp = NULL;
    char *filename = get_filename(selection);
    size_t len = strlen(filename);
    temp = malloc(len + 1);
    if (temp == NULL) {
        /* malloc failed */
    }
    strncpy(temp, filename, len);
    Last edited by oogabooga; 09-04-2013 at 10:29 AM.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    Registered User
    Join Date
    Aug 2011
    Posts
    35
    Thanks. I understand what you are saying. But then I try this, and I still get a segmentation fault:

    Code:
    char* temp;
    temp = malloc(strlen(get_filename(selection))+1);
    strcpy(temp, get_filename(selection));
    Still stuck. Thanks for any advice.

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    That won't work because get_filename has already removed the brackets from your string, replacing them with ascii nuls. You can only call it once on selection unless selection has been reloaded with the string. That's why I only called it once in the code displayed.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  6. #6
    Registered User
    Join Date
    Aug 2011
    Posts
    35
    Wow, I didn't know that. I usually program in Java, and we do this all the time. But what's wrong with this:

    Code:
                    filename = "client/";
                    fprintf(stderr, "%s\n", filename);
    
                    char* temp = get_filename(selection);
                    fprintf(stderr, "%s\n", temp);
    
                    strncat(filename, temp, strlen(temp)-1);
    I get an error: Bus Error 10;

  7. #7
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You've gone back to not allocating any space for temp.
    You have to do the malloc, and you'll have to malloc (at least) enough to hold the final string size.

    Also, I'm not sure why you're subtracting 1 from strlen(temp) ???
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  8. #8
    Registered User
    Join Date
    Aug 2011
    Posts
    35
    This is killing me. A simple string concatenation. Unbelievable.

    Code:
    filename = "client/";
    fprintf(stderr, "filename: %s\n", filename);
                    
    char* temp = get_filename(selection);
    size_t len = strlen(temp);
    
    temp = malloc(len + 1);
    fprintf(stderr, "temp: %s\n", temp);  //EMPTY!!!!!!!!!!!!!!
                    
    filename = malloc(strlen(filename) + strlen(temp) + 1);
    strncat(filename, temp, strlen(temp));
    
    fprintf(stdout, "filename: %s\n", filename); //EMPTY!!!!!!!!!!
    I'm sorry to be so dense, but I am truly frustrated with this language. Can you help me a little more? Thanks.

  9. #9
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    No problem! In some ways it can be more confusing coming from Java to C than learning C as your first language. You have to "unlearn" some things and learn the C way.

    Java is far simpler for memory handling.
    Even C++ is easier (in some ways) than C for memory handling.
    C is a fairly low-level language that doesn't really do anything you don't ask for.
    That's its strength.
    And its weakness.

    So here's how I'd do it:
    Code:
    char *dir = "client/";
    char *filename = get_filename(selection);
    if (filename == NULL) {
        /* get_filename failed */
    }
    char *path = malloc(strlen(dir) + strlen(filename) + 1);
    if (path == NULL) {
        /* malloc failed */
    }
    strcpy(path, dir);
    strcat(path, filename);
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Let's analyse this part:
    Code:
    char* temp = get_filename(selection);
    size_t len = strlen(temp);
     
    temp = malloc(len + 1);
    fprintf(stderr, "temp: %s\n", temp);  //EMPTY!!!!!!!!!!!!!!
    First, you call get_filename and store the result in temp. Then you overwrite temp with the return value of malloc. Then, you print temp, but temp now points to uninitialised storage, hence you risk undefined behaviour.

    I would get rid of these two lines:
    Code:
    temp = malloc(len + 1);
    fprintf(stderr, "temp: %s\n", temp);  //EMPTY!!!!!!!!!!!!!!
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Aug 2011
    Posts
    35
    Thanks. That works. Finally. I guess that I'm confused as to when I have to call malloc and when I don't. A couple of posts ago, I thought you told me that I needed to call malloc after my function returned to allocate the memory. But now I see that this blows away the return value. I guess it makes sense, but it's so non-intuitive to me.

    Thanks for sticking with me. I appreciate it.

  12. #12
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by joatmon View Post
    I guess that I'm confused as to when I have to call malloc and when I don't.
    let's say in java you have classes named foo and bar, and bar contains a function called get_foo() that returns a foo object. you wouldn't do something like this:

    Code:
    bar b = new bar();
    foo f = b.get_foo();
    f = new foo();
    the same thing applies to malloc. you don't call it if you've already assigned something that want to use.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code not working w/ Char
    By Khabz in forum C++ Programming
    Replies: 21
    Last Post: 03-16-2013, 08:14 AM
  2. Working with char
    By Mentallic in forum C Programming
    Replies: 12
    Last Post: 09-06-2011, 08:35 AM
  3. Replies: 9
    Last Post: 11-18-2008, 02:59 AM
  4. Copying one char* to another not working?
    By Saggio in forum C++ Programming
    Replies: 1
    Last Post: 10-10-2006, 06:03 AM
  5. working with char
    By kennny2004 in forum C++ Programming
    Replies: 20
    Last Post: 11-07-2005, 06:33 AM