473,770 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

structure member allocation

I am trying to write this piece of code that reads a config file, in the
format:

ENTRY value

and I want to read the config file, then read the "value" into the
appropriate member of the following structure:

struct conf_data {
char *root;
char *pid_file;
char *log_dir;
char *local_addr;
unsigned int port;
unsigned short child_min;
unsigned short child_max;
};

typedef struct conf_data Config;

I want the 4 char pointers to be dynamically allocated at runtime,
depending on the length of the "value" in the config file.

I have a fuction, get_conf_data that is run from main():

Config *get_conf_data( void)
{
Config *conf;
...
return conf;
}

My question is, do I need to allocate memory for the structure first
then the members, like:

conf = malloc(sizeof(C onfig));
conf->root = malloc(strlen(t his_value));
conf->pid_file = malloc(strlen(t hat_value));

if I do need to do that way, then when I am free()ing, do I do it in the
opposite order?

int main()
{
Config *conf = get_conf_data() ;
...
free(conf->root);
free(conf->pid_file);
...
free(conf);
}

Or am I totally off-base here?

Thanks,
Aaron

Nov 13 '05 #1
4 4078
nrk
Aaron Walker wrote:
I am trying to write this piece of code that reads a config file, in the
format:

ENTRY value

and I want to read the config file, then read the "value" into the
appropriate member of the following structure:

struct conf_data {
char *root;
char *pid_file;
char *log_dir;
char *local_addr;
unsigned int port;
unsigned short child_min;
unsigned short child_max;
};

typedef struct conf_data Config;

I want the 4 char pointers to be dynamically allocated at runtime,
depending on the length of the "value" in the config file.

I have a fuction, get_conf_data that is run from main():

Config *get_conf_data( void)
{
Config *conf;
...
return conf;
}

My question is, do I need to allocate memory for the structure first
then the members, like:

conf = malloc(sizeof(C onfig));
conf->root = malloc(strlen(t his_value));
conf->pid_file = malloc(strlen(t hat_value));

Yes. You need to allocate memory for the structure pointer first, and only
then you can assign to members in the structure pointed to by it (makes
sense, doesn't it?). However note that:
a) conf = malloc(sizeof *conf);
is the clc preferred way of doing this malloc. This avoids coding the type
information of conf in more than one place unnecessarily.

b) conf->root = malloc(strlen(t his_value) + 1);
conf->pid_file = malloc(strlen(t hat_value) + 1);
Do *NOT* *EVER* forget the terminating NUL at the end of c-style strings!!
if I do need to do that way, then when I am free()ing, do I do it in the
opposite order?

int main()
{
Config *conf = get_conf_data() ;
...
free(conf->root);
free(conf->pid_file);
It doesn't have to be strictly in opposite order (as in you can switch the
above two statements around if you want).
...
free(conf);
}


However, you must free all the pointer members inside the structure that
before freeing the pointer to the structure itself.

-nrk.

<snip>
Nov 13 '05 #2
Aaron Walker <ka*****@REMOVE THIScfl.rr.com> wrote in message news:<5a******* **************@ twister.tampaba y.rr.com>...
I am trying to write this piece of code that reads a config file, in the
format:

ENTRY value

and I want to read the config file, then read the "value" into the
appropriate member of the following structure:

struct conf_data {
char *root;
char *pid_file;
char *log_dir;
char *local_addr;
unsigned int port;
unsigned short child_min;
unsigned short child_max;
};

typedef struct conf_data Config;

I want the 4 char pointers to be dynamically allocated at runtime,
depending on the length of the "value" in the config file.

I have a fuction, get_conf_data that is run from main():

Config *get_conf_data( void)
{
Config *conf;
...
return conf;
}

My question is, do I need to allocate memory for the structure first
then the members, like:
Yes if you declare it as a pointer.
conf = malloc(sizeof(C onfig)); conf = malloc(sizeof *conf );/* make sure you include <stdlib.h> */

Note: Check on the return type of 'malloc' always.
conf->root = malloc(strlen(t his_value));
What is 'this_value' declared as ? In case its a string, then -

conf->root = malloc(strlen(t his_value)*size of *conf->root );

conf->pid_file = malloc(strlen(t hat_value));

conf->pid_file = malloc(strlen(t hat_value) * sizeof *conf->pid_file);

if I do need to do that way, then when I am free()ing, do I do it in the
opposite order?

Yes.
int main()
{
Config *conf = get_conf_data() ;
...
free(conf->root);
free(conf->pid_file);
...
free(conf);/* In case conf is a pointer. */
}

Or am I totally off-base here? Post a least compilable code for us to comment more on that !

Thanks,
Aaron

Nov 13 '05 #3
Ravi Uday wrote:
Aaron Walker <ka*****@REMOVE THIScfl.rr.com> wrote in message
news:<5a******* **************@ twister.tampaba y.rr.com>...

conf->root = malloc(strlen(t his_value));


What is 'this_value' declared as ? In case its a string, then -

conf->root = malloc(strlen(t his_value)*size of *conf->root );

conf->pid_file = malloc(strlen(t hat_value));

conf->pid_file = malloc(strlen(t hat_value) * sizeof *conf->pid_file);


Aren't you forgetting something?\0
--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #4
<snip>
conf->root = malloc(strlen(t his_value));


What is 'this_value' declared as ? In case its a string, then -

conf->root = malloc(strlen(t his_value)*size of *conf->root );

conf->pid_file = malloc(strlen(t hat_value));

conf->pid_file = malloc(strlen(t hat_value) * sizeof *conf->pid_file);


Aren't you forgetting something?\0


Yes, I have..You need to add '1' inside the malloc to account for '\0'
Nov 13 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2415
by: Mannequin* | last post by:
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to follow? Second, have I correctly passed the structure's pointer to the functions in this program?
13
7298
by: John | last post by:
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl
15
2780
by: damian birchler | last post by:
Hi I'm wondering of what type a structure is. Of course, it is a _structure_, but an array isn't an _array_ either. So of what type is a structure? I'd say a pointer, am I right?
10
2314
by: ranjeet.gupta | last post by:
Dear All !! Before i qoute my querry, I will like to qoute my analysis and my Knowledge Struct a { int raw; char data; };
8
2471
by: ulyses | last post by:
I'm trying to put pointer to flexible array of structures in other structure. I want to have pointer to array of pixels in screen structure. Here is mine code, but I think it isn't quite all right: struct pixel { int x; int y; int color; };
14
3725
by: Kavya | last post by:
Here is the code int main(){ struct node{ int a; int b; int c; }; struct node s={3,5,6}; struct node *ptr=&s;
17
9147
by: dtschoepe | last post by:
Hi, I have a homework project I am working on, so be forwarned, I'm new to C programming. But anyway, having some trouble with a memory allocation issue related to a char * that is a variable inside of a structure. I keep getting segmentation fault errors and I am having trouble understanding why. Here's the parts of the code in question... This is part of the .h file where the struct us defined...
17
2476
by: Jason Doucette | last post by:
I am converting a C-style unit into a C++ class. I have an implementation function that was defined in the .cpp file (so it was hidden from the interface that exists in the .h file). It uses a structure that is only needed by the implementation, so it were declared in the .cpp file, as well. Now, when converting this into a class, the class definition exists in the .h file, since it's required by the interface. The implementation...
8
2704
by: rahul | last post by:
How is the memory allocated for structures? I need to optimize the memory usage and bit fields are not doing the trick. Any details about the memory allocation for the structures would be a great help. PS - I already have asked this in gcc group. Please refrain from directing me towards other groups.
0
9591
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10228
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10057
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10002
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8883
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7415
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3575
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.