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

Home Posts Topics Members FAQ

Allocate memory to char * variables in structure

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...

enum color { COLORS };
typedef enum color Color;

struct person
{
char *firstName;
char *lastName;
char *hobby;
Color favColor;
char sex;
int age;
};
typedef struct person Person;

struct node
{
struct node *next;
Person client;
};
typedef struct node Node;

Now here is the function that I am having trouble with... If you look
down to the section where this line is found...

member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));

The compiler stops there and generates the seg fault message. Here's
the full function. By the way I have tested the first part of the
function, the file pointer exists and the output to stdout from printf
is working ok until I get the line above. Then the program crashes.

Am I trying to allocate the memory in the wrong way?
Person *createMember(F ILE *infile)
{
char fname[30];
char lname[30];
char sex[10];
char age[10];
char color[20];
char hobby[30];
char *colorS;
Person *member;

if (!feof(infile))
{
fgets(fname, 30, infile);
fgets(lname, 30, infile);
fgets(sex, 10, infile);
fgets(age, 10, infile);
fgets(color, 20, infile);
fgets(hobby, 30, infile);
}

else
return NULL;
printf("top of createMember\n" );
/* read member attributes from file */
fgets(fname, sizeof fname, infile);
fname[strlen(fname)-1] = '\0';
fgets(lname, sizeof lname, infile);
lname[strlen(lname)-1] = '\0';
fgets(sex, sizeof sex, infile);
sex[strlen(sex)-1] = '\0';
fgets(age, sizeof age, infile);
age[strlen(age)-1] ='\0';
fgets(color, sizeof color, infile);
color[strlen(color)-1] = '\0';
fgets(hobby, sizeof hobby, infile);
hobby[strlen(hobby)-1] = '\0';
printf("got through fgets statements.\n") ;

/* create memory allocation for member attributes */
member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));
printf("calloc firstName\n");
member->lastName = (char *)malloc(sizeof (fname) * sizeof(char));
member->hobby = (char *)malloc(sizeof (hobby) * sizeof(char));
colorS = (char *)malloc(sizeof (color) * sizeof(char));
printf("got past malloc statements\n");

/* store member attributes */
strcpy(member->firstName, fname);
printf("fname processed\n");
sscanf(lname, "%s", member->lastName);
sscanf(sex, "%c", member->sex);
sscanf(age, "%d", member->age);
strncpy(colorS, color, sizeof(color));
member->favColor = readColor(color S);
sscanf(hobby, "%s", member->hobby);
printf("bottom of createMember\n" );

return member;
}

David

Mar 5 '07 #1
17 9148
dt*******@gmail .com wrote:
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...
>

Now here is the function that I am having trouble with... If you look
down to the section where this line is found...

member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));
Never cast the return of calloc/malloc/realloc. Also sizeof(char) is by
definition 1. Remove the casts and make sure you have included <stdlib.h>
The compiler stops there and generates the seg fault message.
I assume you should have said the program crashes when you run it?

sscanf(sex, "%c", member->sex);
sscanf(age, "%d", member->age);
the above should use &member->sex and &ember->age.

--
Ian Collins.
Mar 5 '07 #2
dt*******@gmail .com wrote:
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...

enum color { COLORS };
Only one enumeration constant?
typedef enum color Color;

struct person
{
char *firstName;
char *lastName;
char *hobby;
Color favColor;
char sex;
int age;
};
typedef struct person Person;

struct node
{
struct node *next;
Person client;
};
typedef struct node Node;

Now here is the function that I am having trouble with... If you look
down to the section where this line is found...

member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));
sizeof(char) is always one in C. Also no need to cast the return value
of calloc, (or malloc or realloc), as it can hide certain mistakes.
The compiler stops there and generates the seg fault message.
You mean compilation stops with a segmentation fault. If so the
compiler is broken.
Here's
the full function. By the way I have tested the first part of the
function, the file pointer exists and the output to stdout from printf
is working ok until I get the line above. Then the program crashes.

Am I trying to allocate the memory in the wrong way?
Person *createMember(F ILE *infile)
{
char fname[30];
char lname[30];
char sex[10];
char age[10];
char color[20];
char hobby[30];
char *colorS;
Person *member;

if (!feof(infile))
In C, feof and ferror are used _after_ a call to one of the I/O
functions have reported failure.
{
fgets(fname, 30, infile);
fgets(lname, 30, infile);
fgets(sex, 10, infile);
fgets(age, 10, infile);
fgets(color, 20, infile);
fgets(hobby, 30, infile);
Check all these calls for failure. Are you also sure that the various
fields will be less than the array sizes?
}

else
return NULL;
printf("top of createMember\n" );
/* read member attributes from file */
fgets(fname, sizeof fname, infile);
Why are you overwriting fname again?
fname[strlen(fname)-1] = '\0';
This will already be done for you by fgets.
fgets(lname, sizeof lname, infile);
lname[strlen(lname)-1] = '\0';
fgets(sex, sizeof sex, infile);
sex[strlen(sex)-1] = '\0';
fgets(age, sizeof age, infile);
age[strlen(age)-1] ='\0';
fgets(color, sizeof color, infile);
color[strlen(color)-1] = '\0';
fgets(hobby, sizeof hobby, infile);
hobby[strlen(hobby)-1] = '\0';
printf("got through fgets statements.\n") ;
All these statements are duplicates of the what you'd written earlier
within the if construct. The overwrite values read earlier with
possibly wrong values. Is this really what you want?

Also check the fgets statements for failure. Don't simply assume to
have got through safely.
/* create memory allocation for member attributes */
member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));
Here's your main error. member is pointer to a Person type, (which is
actually a struct of type person), but as yet it doesn't point to
valid instance of a Person object. You need to define a Person object,
set member to point to it and then do the memory allocation for the
fields like:

Person p1;
member = &p1;
/* ... */
printf("calloc firstName\n");
member->lastName = (char *)malloc(sizeof (fname) * sizeof(char));
member->hobby = (char *)malloc(sizeof (hobby) * sizeof(char));
colorS = (char *)malloc(sizeof (color) * sizeof(char));
Same as above. Also don't cast return value of *alloc. I'd write these
statements as:
printf("got past malloc statements\n");
Without error checking.
/* store member attributes */
strcpy(member->firstName, fname);
printf("fname processed\n");
sscanf(lname, "%s", member->lastName);
Why strcpy for firstName and sscanf for lastName?
sscanf(sex, "%c", member->sex);
sscanf(age, "%d", member->age);
strncpy(colorS, color, sizeof(color));
member->favColor = readColor(color S);
sscanf(hobby, "%s", member->hobby);
printf("bottom of createMember\n" );

return member;
}
Make sure your Person object is not a local one, since, if so, it'll
get destroyed when execution leaves this function. Either dynamically
allocate the object or make it a file scope one.

Mar 5 '07 #3
On Mar 4, 10:02 pm, Ian Collins <ian-n...@hotmail.co mwrote:
dtscho...@gmail .com wrote:
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...
Now here is the function that I am having trouble with... If you look
down to the section where this line is found...
member->firstName = (char *)calloc(strlen (fname)+1, sizeof(char));

Never cast the return of calloc/malloc/realloc. Also sizeof(char) is by
definition 1. Remove the casts and make sure you have included <stdlib.h>
The compiler stops there and generates the seg fault message.

I assume you should have said the program crashes when you run it?
sscanf(sex, "%c", member->sex);
sscanf(age, "%d", member->age);

the above should use &member->sex and &ember->age.
OK, am I correct in understanding that I should be changing the code
as follows?

member->firstName = calloc(strlen(f name)+1, sizeof(char));

Notice I removed the (char *) from in front of calloc. Actually,
leaving it there is how any example in class had it. So I am confused.

I did also mean the program crashes, not the compiler stops. I am too
tired to think clearly tonight.

By the way, I just recompiled and ran the program by removing the
(char *) cast, but the same seg fault error is still there. I will
need to review my code more.

Also, I am including the stdlib.h library in my header.

David

Mar 5 '07 #4
On Mar 4, 10:04 pm, "santosh" <santosh....@gm ail.comwrote:
Why are you overwriting fname again?
fname[strlen(fname)-1] = '\0';

This will already be done for you by fgets.
Well, according to my handy dandy textbook, Programming in C by
Stephen Kochan, the fgets function will read everything into the array
including the newline character (\n), so I am overwriting the newline
character with the \0 character so I can eliminate the newline
character.

I am reading all the data from a file and each set of data ends with
new line character.

David

Mar 5 '07 #5
dt*******@gmail .com wrote:
>

OK, am I correct in understanding that I should be changing the code
as follows?

member->firstName = calloc(strlen(f name)+1, sizeof(char));
Or just

member->firstName = calloc(strlen(f name)+1, 1);

And take note of the critical bug santosh spotted that I didn't - you
have not allocated any memory for member.
Notice I removed the (char *) from in front of calloc. Actually,
leaving it there is how any example in class had it. So I am confused.
This is a common mistake. All the cast does is suppress important error
messages if you forget to include the header, nothing else.

--
Ian Collins.
Mar 5 '07 #6
On Mar 4, 10:04 pm, "santosh" <santosh....@gm ail.comwrote:
>
else
return NULL;
printf("top of createMember\n" );
/* read member attributes from file */
fgets(fname, sizeof fname, infile);

Why are you overwriting fname again?
You got me there. I wrote that code at two different times and
obviously made a boo-boo. I have deleted the second set of fgets()
statements. Although in the test this didn't hurt anything, I have
enough data in the file to cover the mistake.

I'm working on your other suggestions but to this point I'm still
getting the segfault when the program runs. I think this has something
to do with your reference to me not creating a proper Person.
Here's your main error. member is pointer to a Person type, (which is
actually a struct of type person), but as yet it doesn't point to
valid instance of a Person object. You need to define a Person object,
set member to point to it and then do the memory allocation for the
fields like:

Person p1;
member = &p1;
If I define member using...

Person member;

What is the difference if I use member or p1? In your example, you
didn't associate member with a type. So I'm not sure what relevance
your example has? That being said, your point is a valid one, and I
would like to learn the correct way this is done. Hopefully I can
figure it out, but I just need to figure how the syntax of where I'm
wrong.

David

Mar 5 '07 #7

Santos and Ian,

Thanks for your help. I did review your comments again and see where
my problems were. I am now making progress with the program.

David

Mar 5 '07 #8
dt*******@gmail .com wrote:
Santos and Ian,

Thanks for your help. I did review your comments again and see where
my problems were. I am now making progress with the program.
Good luck!

--
Ian Collins.
Mar 5 '07 #9
dt*******@gmail .com wrote:
On Mar 4, 10:04 pm, "santosh" <santosh....@gm ail.comwrote:
<snip>
I'm working on your other suggestions but to this point I'm still
getting the segfault when the program runs. I think this has something
to do with your reference to me not creating a proper Person.
>Here's your main error. member is pointer to a Person type, (which is
>actually a struct of type person), but as yet it doesn't point to
>valid instance of a Person object. You need to define a Person object,
>set member to point to it and then do the memory allocation for the
>fields like:
>
Person p1;
member = &p1;

If I define member using...

Person member;
>From your first post to this thread:
>>>>>>>>>>>>
Person *createMember(F ILE *infile)
{
char fname[30];
char lname[30];
char sex[10];
char age[10];
char color[20];
char hobby[30];
char *colorS;
Person *member;

if (!feof(infile))
{
<<<<<<<<<<<<<

As you can see, you've declared member as a _pointer_ to an object of
type Person. Now you're saying member is a Person object, not a
pointer. If so, all your accesses to the fields of member by using the
structure indirection operator, (->), is wrong. It can only be used
with pointers to structures. If member is an actual struct object then
use the dot operator to access fields like:

member.firstNam e = /* whatever */

What is the difference if I use member or p1?
No difference. But there *is* a difference between Person *member and
Person member. The former is a pointer to a Person object, while the
latter *is* a Person object.
In your example, you
didn't associate member with a type. So I'm not sure what relevance
your example has? That being said, your point is a valid one, and I
would like to learn the correct way this is done. Hopefully I can
figure it out, but I just need to figure how the syntax of where I'm
wrong.
This is basic structure stuff. Your textbook should have the
information. If not, then it isn't a good C textbook.

Mar 5 '07 #10

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

Similar topics

37
4680
by: Curt | last post by:
If this is the complete program (ie, the address of the const is never taken, only its value used) is it likely the compiler will allocate ram for constantA or constantB? Or simply substitute the values in (as would be required if I used the hideous, evil, much-abused #define :) ----------- const int constantA = 10; static const int constantB = 20;
5
2484
by: lixiaoyao | last post by:
hi all I use matrix & vector function to allocate the space myself in c, typedef struct matrix_array newdata; struct matrix_array{ float **sy,*sxx; }; newdata ndata;//new data struct ndata.sy=matrix(1,nvar,1,nstep); ndata.sxx=vector(1,nstep);
12
5636
by: gc | last post by:
I am writing a function that given nx1 vector a and a nx1 b solves a system of equations f(a,c)=b for a nx1 c. While writing the function: 1] Should I allocate the memory for c within the function and return the allocated memory? something that leads to double *solve(const double *a,const double *b,int n) { double *c;
8
2934
by: vikram | last post by:
i have series of questions 1.How a c program is loaded in memory i mean the whats is the structure that the code segment?? data segment?? 2.When you say const int *p; where is p stored in the memory?? what happens internal so that its a read only. 3. when declared volatile int *p where exactly in the memory it is stored.
9
1955
by: Alfonso Morra | last post by:
Hi, I am having some probs with copying memory blocks around (part of a messaging library) and I would like some confirmation to make sure that I'm going about things the right way. I have some data types defined thus: typedef enum { ONE ,
2
11954
by: vikas | last post by:
I have following structure in c++. typedef struct MMF_result_struct { int action; char text; int cols,rows; int month,day,year; } MMF_result; Now this structure is shared between C++ and C# using memory mapped file. We already have C++ code for handling memory mapped file. I am working on converting code for memory mapped file in C#. Now I have to pass pointer to the above structure. I converted this structure to C# as follows:
14
2641
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
5
1789
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
1
2591
by: sunil | last post by:
Hi, Am developing one shared library for one application. In that .so am having one global array of structure ( two more different structure pointers in this struct). Once the application is launched, then I am allocating the memory on the heap for the internal structures. To print the log messages I am using the below mentioned global variables and time header functions.
0
9618
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
9454
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
10101
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
10038
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
8933
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...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
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.