Question: I have a C string and I'd like to shorten it, so that it gets cut from the first occurrence of '$'. Here's my code:

```
int char_search(char exp[], int s, char what) {
    int i, occurrence=-1;
    for (i=0; i < s && occurrence == -1; ++i)
        if (exp[i] == what)
            occurrence = i;

    return occurrence;
}

int shorten(char *exp, int maxlength, char *exp_new) {
    int l, i;
    l = char_search(exp, maxlength, '$');
    exp_new = (char *) malloc((l+1)*sizeof(char));
    exp_new[l] = '\0';
    for (i = 0; i<l; i++) 
        exp_new[i] = exp[i];

    return l;
}

```

The problem is it starts to overwrite the exp\_new pointer address, and only copies the first char to the actual array. Also, exp\_new returns NULL for some reason. (The string lengths might not be correct, but that shouldn't screw up the whole thing.)

Answer: 
When you want to return a pointer through a function parameter you need to use a double indirection:

```
int shorten(char *exp, int maxlength, char **exp_new)

```

A better signature would be

```
char* shorten(char *exp, int maxlength, int *length)

```

where you return the result directly.

*Edit*: When the function name "shorten" describes what it is ment to do the obvious result should be the shortened string. The length of that string resulting from the search function is a negligible result. The function could be changed so that the length parameter could accept a NULL pointer. In that case you could omitting a length result if it's not interesting for the caller. But that depends on the environment.
There are plenty of bugs in your code. 

`l = char_search(exp, maxlength, '$');` You need to check the result so that it isn't -1.

`(char *) malloc((l+1)*sizeof(char));` You need to check the result of malloc. Also, never cast the result of malloc.

`for (i = 0; i<l; i++)` This doesn't copy the null termination, it is a bit strange that you null terminate first and copy the data afterwards. I would replace the loop with `memcpy(exp_new, exp, l);` and *after that* execute `exp_new[l] = '\0';`.

The true source of the problem is obscure variable names. Nobody, including yourself, can tell what `l` is supposed to mean. Call it `str_length` or something, so that the reader can easily tell that "ah yes this is the length of the string, so it doesn't include null termination". Furthermore `l` and `1` looks exactly the same on some code editors, making it an bad choice of variable name in general.

Also, `exp` should be `const char*` for both functions.

`char *exp_new` stores a pointer on the stack. That pointer only exists throughout the execution of the function. If you want to return the allocated memory to the caller, you must change the parameter to `char** exp_new`. 

Generally however, returning pointers to malloc'd memory is somewhat bad and dangerous practice. Make sure that the memory is freed somewhere.