
-----------------------------------
KG245
Tue Apr 09, 2013 4:48 pm

Question
-----------------------------------
Consider the function:


char **split(char *line) {
    char **strs = malloc(4 * sizeof(char *));
    int i;
    char *p = line;
    for (i = 0; i < 4; i++) {
        strs

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
Mod Edit:
Please wrap you code in either of the following in order to preserve whitespace (indentation) and to highlight the syntax.
 ... code ... 

[code] ... code ... [/code ]
[/code]

-----------------------------------
Tony
Tue Apr 09, 2013 5:24 pm

RE:Question
-----------------------------------
Have you tried making those changes and seeing how the program behaves?

-----------------------------------
Insectoid
Tue Apr 09, 2013 5:30 pm

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
Wed Apr 10, 2013 6:05 pm

RE:Question
-----------------------------------
Also,  if you don't want it to have the function return a value, you can set the function type as void.
