Search code examples
cstringdynamicreallocstrcat

Dynamic sized string in C


I have the following code and to edit the string of a "path" that I will be working on in a program that I am creating.

My problem is that I the code works, but I have no idea why or to be clearer I don't understand why strcat allows src to be appended to dest. Since everything is using dynamic strings shouldn't I have to realloc dest. But when I try that, realloc fails

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

    int main(int argc, char** argv) {
        char *src = argv[1];
        char *dest = argv[2];
        char *d_basedir;
        int s_length = strlen(src);

        printf("dest starts as %s: length %zu\n", dest, strlen(dest));
        printf("src starts as %s: length %zd\n", src, strlen(src));

        if(!(src[s_length - 1] == '/')) {
            if((d_basedir = strrchr(src, '/')+1) != NULL) {
                printf("basedir is %s\n", d_basedir);
                strcat(dest, d_basedir);
                printf("dest changed to %s: length %zd\n", dest, strlen(dest));
            }
        }

        printf("dest ends as %s: length %zd\n", dest, strlen(dest));

        return 0;
    }

Solution

  • The hosted environment provides you with the argv[] array, but you didn't allocate this memory, so you shouldn't attempt to reallocate it. You shouldn't really modify argv[] at all. If you want to make modifications, make a copy of the string first (using malloc etc.) and at least then you can know for certain whether you have enough space or whether you need to use realloc before concatenating.