c - Incorrect values assigned to a member of a structure -


i have structure

 struct services {  char *actived[50];  char *disactived[50];  }; 

and function :

void servicesinfo(struct services *services_i) { file *fp; int status; char *tmp; const char *actived_cmd ="/usr/sbin/service --status-all | awk '/[+]/{ print $4  }'" ;  fp = popen(actived_cmd, "r"); int i=0; while (fgets(tmp, 1024, fp)){     printf("service %s\n", tmp);     (services_i->actived)[i]=tmp;     i++; } status = pclose(fp); 

}

when call function

 struct services services_i;  servicesinfo(&services_i); 

all fine , services printed, if code

for (i = 0; < 20; ++i) {     printf("service i=%d %s\n",i,services_i.actived[i] );        } 

print last value (uvrandom)

you need read on c pointer , memory allocation. there 2 misunderstandings here:

  1. tmp not, written, string buffer. string pointer. can assigned point strings allocated somewhere else, , not contain string itself.
  2. you copying pointer actived (which way should spelled activated). means actived pointers point same tmp does, same, since tmp never changed (and has uninitialized value).

i suggest use tmp = malloc(1024). don't forget use free(services_i.actived[i]) when don't need them anymore.

i suggest making array of structs instead of struct of arrays, make more logical.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -