473,473 Members | 2,826 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

MAllocate memory for structures?

Hi all,

I have to use C-style structures for an assignement. I cannot have any
methods or constructors for it. What has surprised me is that in my
code, I have to allocate memory for an array of structures with malloc.
Otherwise, I get a seg fault. Here's the code:

struct Employee {
char* name; // Pointer to character string holding name of employee.
int salary;
};

// Allocate the employee array;
Employee* emp[20];

int ans; // return value of fscanf
int size = 0;

for (int i = 0; i < MAX_EMPS; i++)
{
//dynamically allocate memory
// otherwise seg fault

emp[i] = static_cast <Employee*> (malloc (sizeof (Employee*)));
emp[i]->name = static_cast <char*> (malloc (MAX_CHARS));

// Read one line of the file
ans = readEmployee(emp[i] , inpfile);

if (ans == -1) {
break;
}

size++;
}

As you can see, I have to call malloc twice, cat the result. Is this
normal? Are there any other ways of avoiding this??

Thanks,
BB
Jul 23 '05 #1
8 4455
Berk Birand wrote:
Hi all,

I have to use C-style structures for an assignement. I cannot have any
methods or constructors for it. What has surprised me is that in my
code, I have to allocate memory for an array of structures with malloc.
Otherwise, I get a seg fault. Here's the code:

Of course, you have two hunks of memory to allocate for each object. That
for the Employee struct itself and for the char's that represent the name.
The othe option is to redefine your struct as:

struct Employee {
char name[MAX_CHARS]; // assuming MAX_CHARS is a constant
int salary;
}

Then you can malloc sizeof(Employee) and the array of chars is contained
within.

Frankly, unless you have to talk to C, this entire exercise is stupid and
a bad design. The segfault you got is a prime example of the kind of
mistakes that crop up that are entirely unnecessary.

Further, you have to free up everything you malloc or else you have a memory
leak (more chances to get it wrong) ... You also run the risk in code
you haven't shown of overrunning the "name" array unchecked, ealso if you
copy the Employee object with the pointer in it, you have to manually
dup the pointer (or write a copy constructor that does the right thing...

If the goal is to program in C++, start out doing it right...it is not
the right way to learn things to do them wrong first and then assume
you'll get better.

class Employee {
std::string name;
int salary;

public:
std::string Name();
int Salary();

void Read(std::istream& in) {
// whatever, you didn't show this
in >> name;
in >> salary;
}
};
std::istream& operator>>(std::istream& in, Employee& e) {
e.Read(in);
return in;
}

int main() {
std::vector<Employee> emp;

while(true) {
Employee e;
if(infile >> e) emp.push_back(e);
else break;
}

std::cout << emp.size();
return 0;
}

See... no overruns possible, no user programmed memory allocation
to screw up, ...
Jul 23 '05 #2
I do agree with the comments of Ron. If you have to follow your
original design however you allocate the memory for the struct twice -
the only call to malloc you need is for the char array.

#include <iostream>

using namespace std;

struct Employee
{
char* name; // Pointer to character string holding name of employee.
int salary;
};

const int MAX_EMPS = 20;
const int MAX_CHARS = 20;

int readEmployee(Employee* e)
{
strncpy(e->name, "test", 5);
return 0;
}

int main(int argc, char* argv[])
{
// Allocate array of pointers at Employee structs
Employee* emp[MAX_EMPS];

int ans; // return value of fscanf

//this step is not necessary, you already have allocated a pointer
in the array
//emp[0] = static_cast<Employee*>(malloc(sizeof(Employee*)));

//allocate memory for the member 'name'
emp[0]->name = static_cast<char*>(malloc(MAX_CHARS));

//this prints nonsense
cout << emp[0]->name << endl;
// Read one line of the file
ans = readEmployee(emp[0]);
// this prints the member
cout << emp[0]->name << endl;

return 0;
}

Jul 23 '05 #3
wi******@hotmail.com wrote:
int main(int argc, char* argv[])
{
// Allocate array of pointers at Employee structs
Employee* emp[MAX_EMPS];

int ans; // return value of fscanf

//this step is not necessary, you already have allocated a pointer
in the array
//emp[0] = static_cast<Employee*>(malloc(sizeof(Employee*)));


He has space for pointers, not for the actual employees. If he needs to
use malloc, it should be this:
emp[0] = static_cast<Employee*>(malloc(sizeof(Employee)));
Jul 23 '05 #4
Ron Natalie wrote:
Of course, you have two hunks of memory to allocate for each object. That
for the Employee struct itself and for the char's that represent the name.
The othe option is to redefine your struct as:
So let's see if I got this straight. When I declare a structure (not a
pointer to one), I don't have to call malloc, since the memory is
automatically allocated on the stack. However, when I have a pointer to
a struct, then I have to manually allocate the memory (on the heap)
where the pointer will point to?

And also, in that case I have to call malloc with sizeof(Employee)
instead of sizeof(Employee*)?

struct Employee {
char name[MAX_CHARS]; // assuming MAX_CHARS is a constant
int salary;
}
Then you can malloc sizeof(Employee) and the array of chars is contained
within. So when I define Employee this way, it's size is set higher than with
just a pointer to char?

This actually made me wonder what char name[20] does. Does the compiler
secretly call malloc and return the pointer, without showing it to the user?

Frankly, unless you have to talk to C, this entire exercise is stupid and
a bad design. The segfault you got is a prime example of the kind of
mistakes that crop up that are entirely unnecessary.

Further, you have to free up everything you malloc or else you have a
memory
leak (more chances to get it wrong) ... You also run the risk in code
you haven't shown of overrunning the "name" array unchecked, ealso if you
copy the Employee object with the pointer in it, you have to manually
dup the pointer (or write a copy constructor that does the right thing...

If the goal is to program in C++, start out doing it right...it is not
the right way to learn things to do them wrong first and then assume
you'll get better.


I agree completely. The problem is that this course is supposed to be a
"Systems Programming" course. We started out with writing entirely with
C++ strings, cout etc.. However, thinking that we also need to know
about the low-level functions, we were introduced to dynamic allocation
and c style string. So we ended up using C constructs in C++.

After spending hours tracking seg faults, at least now I know why C++ is
much more "user-friendly" than C.
Thank you all for your answers,
BB
Jul 23 '05 #5
Kurt Stutsman wrote:
wi******@hotmail.com wrote:
int main(int argc, char* argv[])
{
// Allocate array of pointers at Employee structs
Employee* emp[MAX_EMPS];

int ans; // return value of fscanf

//this step is not necessary, you already have allocated a pointer
in the array
//emp[0] = static_cast<Employee*>(malloc(sizeof(Employee*)));

He has space for pointers, not for the actual employees. If he needs to
use malloc, it should be this:
emp[0] = static_cast<Employee*>(malloc(sizeof(Employee)));


I couldn't get this code to work. I first changed the definition of the
data structure to hold an array of MAX_CHARS characters, and thus
removed the malloc that was supposed to allocate memory for "name".

When I also comment out the line where malloc(sizeof(Employee)) is, I
get a seg fault.

Also, when I have that line, changing sizeof(Employee*) to
sizeof(Employee) doesn't seem to make a difference, as it works both ways...

Moreover I fail to understand the reason why that allocation is not
required. Suppose I had a structure of just integers. Then wouldn't I
still need to allocate memory for it using

emp[0] = static_cast <Employee*> (malloc (sizeof(Employee)));
Thanks again for the answer...
BB
Jul 23 '05 #6
Berk Birand wrote:
He has space for pointers, not for the actual employees. If he needs
to use malloc, it should be this:
emp[0] = static_cast<Employee*>(malloc(sizeof(Employee)));

I couldn't get this code to work. I first changed the definition of the
data structure to hold an array of MAX_CHARS characters, and thus
removed the malloc that was supposed to allocate memory for "name".

When I also comment out the line where malloc(sizeof(Employee)) is, I
get a seg fault.

You can't comment out the allocation line with how you're setting up
your array. You create an array of Employee pointers. They point to
somewhere in memory where an Employee object exists. Initially, each
element in the array has some undefined value. You need to allocate
space for the Employee object. That's where malloc comes in.
sizeof(Employee) is the size of an employee object, where
sizeof(Employee*) is the size of a pointer to Employee. Therefore you
need to allocate sizeof(Employee) bytes and assign it to the array as I
showed you above.

Also, when I have that line, changing sizeof(Employee*) to
sizeof(Employee) doesn't seem to make a difference, as it works both
ways...
It makes a big difference. it's the difference between allocating
MAX_CHARS + sizeof(int) and sizeof(Employee*) which on many platforms is
the same as sizeof(int) [that's not guaranteed though, merely for
thought]. So when you try to use the object after only allocating
sizeof(Employee*) bytes, there are MAX_CHAR more bytes that you're
overrunning.
Moreover I fail to understand the reason why that allocation is not
required. Suppose I had a structure of just integers. Then wouldn't I
still need to allocate memory for it using

emp[0] = static_cast <Employee*> (malloc (sizeof(Employee)));


Yes.

Also, I don't remember seeing anyone say this because others were
suggesting using vector<> (a good idea), but malloc() can be a real
hassle in C++ because classes and structures can have constructors and
destructors, wihch malloc() and free() do not call. The "new" operator
and "delete" operator will accomplish this, however. Although your
structure is a POD type, and for POD types it doesn't matter, in C++ if
you need to allocate memory you should get used to using new/delete. It
would look like this:
emp[0] = new Employee; // allocate it
.... do some stuff with it ...
delete emp[0]; // free it

For this, though, direct allocation really isn't necessary. I'd suggest
following the other suggestion of using std::vector<Employee>.
Jul 23 '05 #7

"Berk Birand" <gr******@yahoo.com>, haber iletisinde sunlari
yazdi:1109013010.cb68e1d81b91a0ebae0c3c195dde9f1e@ teranews...
Hi all,

I have to use C-style structures for an assignement. I cannot have any
methods or constructors for it. What has surprised me is that in my
code, I have to allocate memory for an array of structures with malloc.
Otherwise, I get a seg fault. Here's the code:

struct Employee {
char* name; // Pointer to character string holding name of employee.
int salary;
};

// Allocate the employee array;
Employee* emp[20];

int ans; // return value of fscanf
int size = 0;

for (int i = 0; i < MAX_EMPS; i++)
{
//dynamically allocate memory
// otherwise seg fault

emp[i] = static_cast <Employee*> (malloc (sizeof (Employee*)));
emp[i]->name = static_cast <char*> (malloc (MAX_CHARS));

// Read one line of the file
ans = readEmployee(emp[i] , inpfile);

if (ans == -1) {
break;
}

size++;
}

As you can see, I have to call malloc twice, cat the result. Is this
normal? Are there any other ways of avoiding this??

Thanks,
BB


With only one malloc() (or new), I would do it like this:

// calculate how much we need
// layout is like this:
// first MAX_EMPS of Employee structures followed by the space allocated for
the names.
size_t sizeToAlloc = MAX_EMPS*(sizeof(Employee) + MAX_CHARS);
Employee* emp = (Employee*)malloc(sizeToAlloc); // go get it -- just once

// now set all pointers
char* pName = (char*)&emp[MAX_EMPS]; //point to the first name
int ix = 0;
while (ix < MAX_EMPS)
{
// set the pointer to the valid memory
emp[ix].name = &pName[ix*MAX_CHARS];

// init employee structrue
emp[ix].name[0] = 0;
emp[ix].salary = 0;
++ ix; //next
}
// all set -- use 'em anyway you want
....
free(pEmp); // just one free is enough
Jul 23 '05 #8
Berk Birand wrote:
So let's see if I got this straight. When I declare a structure (not a
pointer to one), I don't have to call malloc, since the memory is
automatically allocated on the stack. However, when I have a pointer to
a struct, then I have to manually allocate the memory (on the heap)
where the pointer will point to?
Correct.
And also, in that case I have to call malloc with sizeof(Employee)
instead of sizeof(Employee*)?

Yes. You're allocating an "Employee" sized thing not a "ponter to
Employee" sized thing.
So when I define Employee this way, it's size is set higher than with
just a pointer to char?
Yes, rather than a pointer, it contains an array of 20 char's. The size
differential will be approximately 20*sizeof(char) - sizeof(char*).
This actually made me wonder what char name[20] does. Does the compiler
secretly call malloc and return the pointer, without showing it to the
user?
Nope, it just allocates 20 char's inline with the rest of the struct...it's
sort of like you said:
struct Employee {
char name0, name1, name2, ...;
I agree completely. The problem is that this course is supposed to be a
"Systems Programming" course. We started out with writing entirely with
C++ strings, cout etc.. However, thinking that we also need to know
about the low-level functions, we were introduced to dynamic allocation
and c style string. So we ended up using C constructs in C++.


It's still wrong.

I've been a system's programmer for years, and you need to go about it the
other way around. The whole concept of systems programming is maintainability
and reliability. Take a top down approach.
Jul 23 '05 #9

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

Similar topics

15
by: berthelot samuel | last post by:
Hi, I'm trying to develop an application for modeling 3D objects from Bezier patches, but I have a memory allocation problem. Here are my structures: typedef struct _vector3 { union { struct...
5
by: Migrators | last post by:
1)How is the memory structure organised in C. i.e., the way in which the stack and heap memory are used in C. 2) What will be the value of EOF.
5
by: mikegw | last post by:
Hello all. I am currently using an implementation of sysV shared memory. The entire shared memory is allocated is one continuous block of which I get the pointer to the head, everything should...
3
by: nkrisraj | last post by:
Hi, I have a following structure: typedef struct { RateData rdr; int RateID; char RateBalance; } RateInfo;
8
by: nkrisraj | last post by:
Hi, I have a following structure: typedef struct { RateData rdr; int RateID; char RateBalance; } RateInfo;
11
by: skumar434 | last post by:
Hi everybody, I am faceing problem while assigning the memory dynamically to a array of structures . Suppose I have a structure typedef struct hom_id{ int32_t nod_de; int32_t hom_id;
3
by: arne.muller | last post by:
Hello, I've read in the FAQ that modern versions of malloc/free can cache memory, i.e. free does not return memory to the OS so that it may be re-used by the next malloc call. I was thinking...
94
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring...
4
by: Tom | last post by:
I am seeking an efficient method to "clip" the front-end off a large block of memory. For example, let's say there is a block of memory holding 100,000 structures of "data" and you want to drop the...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.