Home Ask Login Register

Developers Planet

Your answer is one click away!

user3011195 February 2016

Incorrect values assigned to a member of a structure

I have a structure

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

and a 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);
status = pclose(fp);


when i call the function

 struct services services_i;

all is fine and all services printed, but if this code

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

print just the last value (uvrandom)


Jesse Louis February 2016

Here is some example code of how to assign a value to structure:

#include <stdio.h>

struct date {           /* global definition of type date */
    int month;
    int day;
    int year;


    struct date  today;

    today.month = 10;
    today.day = 14;
    today.year = 1995;

    printf("Todays date is %d/%d/%d.\n", \
        today.month, today.day, today.year );

StellarVortex February 2016

You need to read up on C pointer and memory allocation. There are two misunderstandings here:

  1. tmp is not, as it is written, a string buffer. It is just a string pointer. It can only be assigned to point to strings that are allocated somewhere else, and not contain the string itself.
  2. You are just copying the pointer to actived (which by the way probably should be spelled activated). This means that all actived pointers all point to the same as tmp does, which is always the same, since tmp is never changed (and also has uninitialized value).

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

I also suggest making an array of structs instead of a struct of arrays, to make it more logical.

Post Status

Asked in February 2016
Viewed 1,361 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life