468,765 Members | 878 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,765 developers. It's quick & easy.

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 4216
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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

15 posts views Thread by berthelot samuel | last post: by
5 posts views Thread by Migrators | last post: by
3 posts views Thread by arne.muller | last post: by
4 posts views Thread by Tom | last post: by
reply views Thread by Marin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.