0

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?

Isac
  • 1,834
  • 3
  • 17
  • 24
J-Dizzle
  • 4,861
  • 4
  • 40
  • 50

1 Answers1

2

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");
}
Abhishek Keshri
  • 3,074
  • 14
  • 31
  • Well in real life application, one would have to somehow ensure he allocate enough memory... so probably the allocation should be done inside getName so that you could compute actual required size... alternatively, you could have a parameter that tell allocated size... In all case, you should free the memory. – Phil1970 Apr 14 '18 at 14:07
  • is it okay now? – Abhishek Keshri Apr 14 '18 at 14:12
  • Well if getName always returns a string of 4 characters + '\0', then yes it will works... but it is fragile if at some point the code is modified to return a longer string... In a toy program, this is not really a proble’m but in large application, it might be hard to ensure that allocated size is updated for every caller. – Phil1970 Apr 14 '18 at 14:21
  • we will need to add realloc for those cases – Abhishek Keshri Apr 14 '18 at 14:22