I'm trying to write simple function trim space in the string in ansi C.
My str_utis.h:
#include <string.h>
const char* trim_str(char *input_str);
My str_utils.c:
const char* trim_str(char* input_str){
char* str = NULL;
int len = strlen(input_str);
int i = 0;
for (i = 0; i < len - 1; i++){
if (input_str[i] == ' ')
;
else
str += input_str[i];
}
return str;
}
When i try to execute it i got segfault:
int main(int argc, char** argv) {
const char* a = trim_str("Hey this is string");
printf("%s", a);
return 0;
}
why is it wrong? how can i write it correctly?
Thank you.
You cannot modify a string literal. It's UB. Copy the string out and modify its contents. Change
to
and then proceed to copy out the non-whitespace contents.