Independent variations on string manipulation in C

I am experiencing a very annoying problem in C:

I wrote this function to encapsulate any string with {}

:

char* encapsule(char* string) {
    char* output;
    int n;

    n = strlen(string);
    output = malloc((n+3)*sizeof(char));
    output[0] = '{';
    strcat(output,string);
    output[n+1] = '}';
    output[n+2] = '\0';

    return output;
}

      

When I use this in my main function like this, it works like a charm:

char* foo = encapsule(getTest());
printf("foo : %s\n",foo);

      

( getTest()

gives 001

and encapsule(getTest())

gives {001}

)

Now when I use this in a helper function like:

long ligne1(FILE* tex_file, long cursor) {
    char* line;
    char* save_text;
    char* foo;

    foo = encapsule(getTest());
    printf("foo : %s\n",foo);

    save_text = copyFile(tex_file);
    rewind(tex_file);
    line = readLine(tex_file,1);
    fseek(tex_file, rightPlace(line), SEEK_SET);
    fputs(foo, tex_file);

    cursor = ftell(tex_file);
    fputs(save_text, tex_file);
    fseek(tex_file,cursor,SEEK_SET);

    return cursor;
}

      

printf gives me: { }

and writes {à}

to a file.

I really don't understand why the behavior of this function is screwing up ...

Thanks for your future help, hopefully!

+3


source to share


2 answers


Here

strcat(output,string);

      

strcat

first finds \0

in output

. Where is the NUL terminator? You haven't assigned it. So your code demonstrates the Undefined Behavior .



Two ways to fix the problem:

  • Switch malloc

    to calloc

    :

    output = calloc( n+3 , sizeof(char));
    
          

  • Add to

    output[1]='\0';
    
          

    just before strcat

    .

+8


source


The function is invalid because you are using the strcat function on a null terminated string

strcat(output,string);

      

The actual function might look like



char* encapsule( const char *string ) 
{
    char *output;
    size_t n;

    n = strlen( string );
    output = malloc( ( n + 3 ) * sizeof( char ) );

    output[0] = '{';
    output[1] = '\0';
    strcat( output, string );
    output[n+1] = '}';
    output[n+2] = '\0';

    return output;
}

      

Another approach is to use strcpy

instead strcat

. for example

char* encapsule( const char *string ) 
{
    char *output;
    size_t n;

    n = strlen( string );
    output = malloc( ( n + 3 ) * sizeof( char ) );

    output[0] = '{';
    strcpy( output + 1, string );
    output[n+1] = '}';
    output[n+2] = '\0';

    return output;
}

      

+4


source







All Articles