• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 237
  • Last Modified:

values to Structure


how can i pass values to a structure at runtime....from a file"A" with two lines in it. Using C.

lets suppose..........my senario:-
FILE  "A"--
typedef struct
{ char *name;
 char * serverIPaddress;
typedef Server1 myServer;
i have to construct "myServer" structure using values from file.

using fgets i am getting the values and had even split them..but when i am trying to assign the value(S) to structure.....some thing is going wrong...both items in structure point to same memory..according my code. there fore is overwritten always.

how to avoid this.??

lets suppose  
while(fgets(filestr,50,FileSource)!=NULL) {
				OK = FillServerInfo(filestr); //where filestr is char*
loop 1:
FillServerInfo(char *str)   //lets suppose str contains string "name=server" in it
   char *strtemp
  // i split the value in str and only send the data through strtemp
    strtemp = strtok(filestr,"=");
   a = getnum(strtemp);  // returns the numeric value of strtemp. name=1,serverIp=2;
   strtemp = strtok(NULL,"=");
  case 1:
      myServer->name = strtemp;
      return 1;
  case 2:
  return  1;
will get correct value in myServer->name......but in next loop it is updated to serverIpaddress values.

Open in new window

  • 3
  • 2
1 Solution
The problem is that you use the same filestr buffer to read each line, and then the strtemp returned by strtok will always point within that buffer, even if the buffer changes.

What you have to do, is change this :

>>       myServer->name = strtemp;

to something like :

        myServer->name = (char*) malloc(strlen(strtemp) + 1);
        strcpy(myServer->name, strtemp);

in order to copy the data, rather than copy the pointer.
>> What you have to do, is change this :

Same for the ip of course.
I aggree with infinity.

I can just add : myServer->name = strup(strtemp);

wich does the same thing than malloc & strcpy
If your platform supports strdup, then that's indeed an alternative, although less portable.
Yes strdup, sorry for the typo.

And you're right for the portability :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Managed Security Services Webinar - March 15

Selecting the right managed security services platform to grow your business can be a huge undertaking. Join WatchGuard and Frost & Sullivan in an upcoming webinar as we dive into the key elements of selecting a vendor platform and partnership to fuel a successful MSSP business.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now