Mostly, you're returning the wrong thing - a modified buf
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *my_strchr( const char *str, int c )
{
while ( *str )
{
if ( *str == c )
{
// only malloc if we actually copy something
char *buf = malloc( strlen( str ) + 1 ); // forgot the +1
char *temp = buf; // buf is returned, dont change it
while ( *str )
*temp++ = *str++;
*temp = 0;
return buf;
}
str++;
}
return NULL;
}
int main ( ) {
char *text = "hello world!";
char *new;
new = my_strchr( text, 'w' );
printf( "%p %s\n", new, new ? new : "(null)" );
new = my_strchr( text, 'z' );
printf( "%p %s\n", new, new ? new : "(null)" );
return 0;
}