Search code examples
cstringmemory-mapped-files

Expanding string without concatenation


How can I expand a string without declaring any other strings in order to concatenate them with the source string?


                            // Figuratively clarification:

char *string = malloc(16);
strcpy(string, "Stack / Overflow");
&string[5] = expand(5);

                                 // Result (In-memory):

Idx: 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21
Chr: S  t  a  c  k  \0 \0 \0 \0 \0     /       O   v   e   r   f   l   o   w   \0

Solution

  • #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char *expand(char *s, int index, int size){
        size_t new_size = strlen(s) + size + 1;
        char *temp = realloc(s, new_size);
        if(temp == NULL){
            fprintf(stderr, "realloc error!\n");
            free(s);
            exit(EXIT_FAILURE);
        }
        s = temp;
        memmove(s + index + size, s + index, strlen(s + index)+1);
        memset(s + index, '\0', size);
        return s;
    }
    
    int main(void) {
        char *sentence = "Stack / Overflow";
        char *string = malloc(strlen(sentence) + 1);
        int i;
    
        strcpy(string, sentence);
        string = expand(string, 5, 5);
        printf("Idx: ");
        for(i=0; i <= 21; ++i)
            printf("%3d", i);
    
        printf("\nChr: ");
        for(i=0; i <= 21; ++i){
            if(string[i])
                printf("%3c", string[i]);
            else
                printf("%3s", "\\0");
        }
        printf("\n");
        free(string);
        return 0;
    }