Search code examples
cstringstrcpy

Appending to string as input argument


I am having trouble generating a string inside a C routine.

Goal

  • Have function generate a custom string and return the value
  • e.g. 'void getName( char ** name )'

Attempt

int main(void) {
    char *name;
    getName(&name);
}

void getName(char **name) {
    *name = "#";                    // Load with prefix
    //?strcpy(*name[1], "123");     // Goal: "#123"
}

How can I have getName() generate #123 as shown here?


Solution

  • 1st problem: use malloc to allocate memory.

    char *name = malloc(sizeof("#123")+1);
    

    Even if you will run it after allocating memory, it will give runtime error; as you are doing:

    *name = "#";
    

    The problem is first you allocate space for 5 chars and point your pointer to the beginning of that memory. Then in the second line you point your pointer to a string literal causing a memory leak.

    The pointer no longer points to the allocated memory.

    You will like to do this:

    int main(void) {
        char *name = malloc(sizeof("#123")+1);
        getName(&name);
        printf("%s", name);
        free(name);
        name = NULL;
    }
    
    void getName(char **name) {
       strcpy((*name), "#");
       strcat(*name,"123");
    }