Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Question
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
KG245




PostPosted: Tue Apr 09, 2013 4:48 pm   Post subject: Question

Consider the function:

c:

char **split(char *line) {
    char **strs = malloc(4 * sizeof(char *));
    int i;
    char *p = line;
    for (i = 0; i < 4; i++) {
        strs[i] = p;
        p = strchr(p, ',');
        *p = '\0';
        p++;
    }
}


There's two problems with it which will cause segfault.
1) I'm not returning char **
2) first line inside for loop should be *strs[i] = p;

Am I right?



Mod Edit:
Please wrap you code in either of the following in order to preserve whitespace (indentation) and to highlight the syntax.
code:

[syntax="c"] ... code ... [/syntax]

[code] ... code ... [/code ]
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: Tue Apr 09, 2013 5:24 pm   Post subject: RE:Question

Have you tried making those changes and seeing how the program behaves?
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Insectoid




PostPosted: Tue Apr 09, 2013 5:30 pm   Post subject: RE:Question

1) You aren't returning anything. This isn't a problem unless you try to access the return value (which is nothing), which will indeed cause a segfault, if the code will even compile.

2) strs() is a pointer to a pointer to a character, or more simply, an array of strings. Therefore, strs[i] points to a string. Since p is a string, that's just fine.

Note that strchr returns NULL if the character is not found. Presumably, your input string contains four phrases ("Chris, Sarah, Amy, Bob"). Your function will correctly split the first 3 phrases off at the comma and replace the comma with a terminating null character ('\0'). When it reaches the fourth word, it will not find a comma. Instead it will reach the end of the string and return NULL. You then attempt to assign the value at *p to '\0', but since p == NULL, it generates a segfault. This is likely your bug.
Cancer Sol




PostPosted: Wed Apr 10, 2013 6:05 pm   Post subject: RE:Question

Also, if you don't want it to have the function return a value, you can set the function type as void.
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: