How can I add a char on the begining of a string in C?

1

I'm trying to put a char on the begining of a string but when I print the final string the result is:

Process finished with exit code -1073741819 (0xC0000005)

This is my code:

char * letter=malloc(strlen(output)+2);
letter[0]='a';
strcat(letter,output);
output=malloc(strlen(output)+2);
strcpy(output,letter);
free(letter);
printf("\n%s",output);

output is string input that i give to the method.

c
char
dynamic-memory-allocation
c-strings
asked on Stack Overflow Aug 29, 2020 by Ludovico Latini • edited Aug 29, 2020 by Vlad from Moscow

1 Answer

2

To use strcat the destination array shall contain a string. Your array letter does not contain a string.

You could write for example

letter[0] = 'a';
letter[1] = '\0';
strcat( letter, output );

or just

letter[0] = 'a';
strcpy( letter + 1, output );

Pay attention to that it seems this statement

output=malloc(strlen(output)+2);

produces a memory leak because the previously allocated memory pointed to by the pointer output was not freed.

The task could be done without allocating a memory for an auxiliary array. You could use the standard function realloc to reallocate the original array pointed to by output. And then move the stored string using memmove to the right one position and then insert the character 'a' in the first position.

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    size_t n = 5;
    char *s = malloc( n * sizeof( char ) );
    strcpy( s, "ello" );
    
    char *tmp = realloc( s, ( n + 1 ) * sizeof( char ) );
    
    if ( tmp != NULL )
    {
        s = tmp;
        memmove( s + 1, s, n );
        s[0] = 'H';
        ++n;
    }
    
    puts( s );
    
    free( s );
    
    return 0;
}

The program output is

Hello
answered on Stack Overflow Aug 29, 2020 by Vlad from Moscow • edited Aug 29, 2020 by Vlad from Moscow

User contributions licensed under CC BY-SA 3.0