for(i=0;i<strlen(expression);i++){
This is very inefficient. strlen(expression)
gets computed at every loop (so you get an O(n2) complexity, unless the compiler is clever enough to prove that expression
stays a constant string and then to move the computation of strlen(expression)
before the loop.....). Should be
for (i=0; expression[i]; i++) {
(since expression[i]
is zero only when you reached the terminating null byte; for readability reasons you could have coded that condition expression[i] != '\0'
if you wanted to)
And as dasblinkenlight answered you should not compute the strlen
on an uninitialized buffer.
You should compute once and for all the strlen(expression)
i.e. start with:
size_t exprlen = strlen(expression);
and use exprlen
everywhere else instead of strlen(expression)
.
At last, use strdup(3):
after = (char*) malloc(sizeof(char)*( strlen(expression)- position+1));
strncpy(after,expression+position+1,strlen(expression)-position+1);
after[strlen(after)]='\0';
should be
after = strdup(expression-position+1);
and you forgot a very important thing: always test against failure of memory allocation (and of other system functions); so
before = (char*) malloc(sizeof(char)*(position +1));
should really be (since sizeof(char)
is always 1):
before = malloc(position+1);
if (!before) { perror("malloc of before"); exit(EXIT_FAILURE); };
Also, if the string pointed by expression
is not used elsewhere you could simply clear the char
at the found position
(so it becomes a string terminator) like
if (position>=0) expression[position] = `\0`;
and set before=expression; after=expression+position+1;
At last, learn more about strtok(3), strchr(3), strstr(3), strpbrk(3), strsep(3), sscanf(3)
BTW, you should always enable all warnings and debugging info in the compiler (e.g. compile with gcc -Wall -g
). Then use the debugger (like gdb
) to step by step and understand what is happening... If a memory leak detector like valgrind is available, use it.