473,770 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
+ 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(em p[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 4484
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::istre am& 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<Emp loyee> 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(Em ployee* 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<Emp loyee*>(malloc( sizeof(Employee *)));

//allocate memory for the member 'name'
emp[0]->name = static_cast<cha r*>(malloc(MAX_ CHARS));

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

return 0;
}

Jul 23 '05 #3
wi******@hotmai l.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<Emp loyee*>(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<Emp loyee*>(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******@hotmai l.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<Emp loyee*>(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<Emp loyee*>(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(E mployee)) 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(Employe e)));
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<Emp loyee*>(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(E mployee)) 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(Employe e)));


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<Emp loyee>.
Jul 23 '05 #7

"Berk Birand" <gr******@yahoo .com>, haber iletisinde sunlari
yazdi:110901301 0.cb68e1d81b91a 0ebae0c3c195dde 9f1e@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(em p[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*(sizeo f(Employee) + MAX_CHARS);
Employee* emp = (Employee*)mall oc(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
1602
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
3595
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
1908
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 be done as offsets from this. At the moment I have two data structures, a head to a linked list which in it contains the pointer to the first element in the linked list( this is redundant as far as I can work out) and the list itself. The data...
3
2357
by: nkrisraj | last post by:
Hi, I have a following structure: typedef struct { RateData rdr; int RateID; char RateBalance; } RateInfo;
8
3022
by: nkrisraj | last post by:
Hi, I have a following structure: typedef struct { RateData rdr; int RateID; char RateBalance; } RateInfo;
11
3786
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
1548
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 about writing some kind of high level memory manger for a scientific project, but then I may just be better off with malloc/free ... . Here's the background: I need to allocate lots of vectros, matrices and structures iteratively, specificly - I...
94
4771
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 that I found inside of a string. Any ideas?
4
3633
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 first 20,000 structures and free that memory. Must the program overwrite the first 80,000 structures? for(int i = 0; i < 80000; ++i) data = data; Followed by a realloc() call. Thus effectively clipping off the
0
9432
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
10232
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...
1
10008
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
9873
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8891
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
7420
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
6682
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
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2822
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.