1

I have a struct containing char** and I need to assign its members in a function, but the following assignment doesn't work:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
    char **clist;
} rule;

void assign(rule *rule) {
    char buf[128] = "hello";
    rule->clist[0] = buf;
}

int main()
{
    rule rule;
    rule.clist = malloc(sizeof(char*) * 8);

    assign(&rule);
    printf("%s\n", rule.clist[0]);

    return 0;
}

Assigning as follows in the main function works though:

char buf[] = "hello";
rule.clist[0] = buf;
Lurkki
  • 17
  • 2
  • 2
    In the `assign` function, the variable `buf` is a *local* variable whose lifetime will end as the function ends, leaving you with an invalid pointer. There's plenty of duplicates about this here on Stack Overflow. – Some programmer dude May 14 '19 at 10:15
  • 1
    Read the chapter in your C book about C-strings. It'll be early on. – Lightness Races in Orbit May 14 '19 at 10:16
  • Also don't use problem descriptions like "it works" and "it doesn't work"; they do not tell us anything. – Lightness Races in Orbit May 14 '19 at 10:16
  • If ```buf``` is declared as a variable in the main program what needs to be done if you want to use that variable in ```assign``` ? – Jon Guiton May 14 '19 at 10:18
  • do yourself a favour and enable all warnings in your C compiler (or even make them errors if possible). If you are using gcc, for example, add `-Wall -Werror` to your compiler command line – mfro May 14 '19 at 10:22
  • If `rule->clist[0]` will only be set to predefined strings, you could use the string literals directly, like `rule->clist[0] = "hello";` but then you wouldn't be able to modify the contents of the string, only replace the string. – Ian Abbott May 14 '19 at 10:24

2 Answers2

0

char buf[128] is stack allocated within the context of the assign function. it can't be passed down in this way because after the function returns the memory is gone. You need to use char *buf; and then do buf = malloc(128); instead.

river
  • 1,028
  • 6
  • 16
0

The Buf string you use in Assign function is local vairable of assign function. it means that after you quit the scope of the assign function, you wont be able to access this memory (its going to be garbage).

To fix it you could use 2 methods:

  1. create the buf string in the data segment (i.e create it as a static/global vairable) or in the heap (use malloc).

  2. use strcpy to copy the data within buf into rule.clist[0].

This should work:

void assign(rule *rule) {
    char buf[128] = "hello";
    rule->clist[0] = (char*)malloc(sizeof(char)*(strlen(buf)+1));
    strcpy(clist[0],buf);
}

int main()
{
    rule rule;
    rule.clist = malloc(sizeof(char*) * 8);

    assign(&rule);
    printf("%s\n", rule.clist[0]);

    return 0;
}
Yoni Newman
  • 185
  • 13