Dominique Léger <> wrote:
>Hello guys,
>
>I'm kinda new to C, and I'm having a hard time with strings. What I'm trying
>to do is a simple function that trims spaces & tabs at the beginning of a
>given string. For example, I want this: " Hello World" to become this:
>"Hello World". At first glance, my function seems to work, but returns some
>strange values...
>
>Here's my code (please pardon the mess):
>
>#include <stdio.h>
>#include <string.h>
#include <ctype.h> /* for isspace */
>int main(void){
> char *trimbegin(char *text);
Function prototypes shouldn't be buried in function definitions,
IMO. Move the prototype outside main, or define trimbegin before
main.
> char *str = " Hello World!";
> char *result = trimbegin(str);
> printf("What the function returns: \"%s\"\n", result);
> return 0;
>}
>
>char *trimbegin(char *text){
> int i = 0, j = 0, ok = 0;
> int size = strlen(text);
> char buffer[size + 1];
> char *ptr;
>
> printf("Original text is: \"%s\"\n", text);
> printf("That's %d characters long...\n", size);
> printf("Now, our text buffer can contain %d characters\n", size +
>1);
> for (i = 0; i <= size; i++){
> if (ok == 1){
> buffer[j] = text[i];
> j++;
> }
> else if (isspace(text[i]) == 0 && ok == 0){
> buffer[j] = text[i];
> j++;
> ok = 1;
> }
> }
That's a very complicated way to do the job at hand.
> printf("What the result is supposed to be: \"%s\"\n", buffer);
> ptr = buffer;
Obfuscation is not a cure for undefined behaviour...
> return ptr;
... which you invoke here by returning an invalid address, since
buffer will be gone when control reaches end of function.
Either
- qualify buffer static (rendering the function non-reentrant
and making C99 VLAs impossible to use), or
- provide a second parameter and let the caller provide the
buffer, or
- dynamically allocate memory for buffer in the function and
document that the caller has to free the memory if it's no
longer needed, or
- return only a pointer to the first non-whitespace character
in the original string,
whatever fits your needs best.
The last one is particularly easy to implement:
char *skipspace( char *s )
{
while ( isspace( *s ) )
s++;
return s;
}
>}
>
>And here's the output:
>
>[dom@localhost C]$ ./a.out
>Original text is: " Hello World!"
>That's 14 characters long...
>Now, our text buffer can contain 15 characters
>What the result is supposed to be: "Hello World!"
>What the function returns: "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿"
>
>
>Why does it return "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿" and not "Hello
>World!"?
You were lucky, because you invoked undefined behaviour, didn't
get what you expected (indicating that something's wrong) and
nothing really serious happened.
HTH
Regards
--
Irrwahn Grausewitz ()
welcome to clc :
http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list :
http://www.eskimo.com/~scs/C-faq/top.html
acllc-c++ faq :
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html