473,608 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc problem in C++

I've inherited some old C code that I've been tasked to convert to C++.
I've been running into some problems with memory allocation.

First of all, is there any problems using "malloc" in C++? I know using
"new" is preferable, but for now I have to use what is provided.

Second, do FILE pointers need to have memory allocated?

My specific problem is this: (all code examples are abbreviated for
clarity)

I have a class

class TObjectDef
{
public:
char *cpFileName;
int iRecordLength;
int iCurrentRecord;
long lRecordCount;
FILE *tpFilePointer
char cpRecBuf[2048];
}

which is initialized

gsPpk = new TObjectDef();

then, much later in the code (about 80k lines later), a float array is
initialized from this structure

(definition
struct DataSegments
{
char caDataId[6];
int iDataCount;
float *fpArr1;
float *fpArr2;
}
)

like so

void vSetFpArray(str uct DataSegments *spDataSeg, float *fpArr1, float
*fpArr2)
{
int iDataCount;
int iDataIndex;

iDataCount = spDataSeg->iDataCount;
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);

for (iDataIndex = 0; iDataIndex < iDataCount; iDataIndex++)
{
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
}
return;
}

The function is called like

vSetFpArray(&sD ataSegments[currInd],floatArray1,fl oatArray2);

where the variables are defined as
static DataSegments sDataSegments[512];
float floatArray1[1024];
float floatArray2[1024];

The function above gets called just fine 318 times. On the 319th iteration,
when "malloc" is called, it is overwriting part of the previously defined
class (which is global to this function). The tpFilePointer goes from being
NULL to being "1" after the first malloc, and "2" after the second. (as in,
pointing to memory address :00000002).

Can anyone see any obvious problems with all this that I may have
overlooked? (Besides the obvious problems with global classes and such.) I
apologize if this question didn't make any sense, I'm happy to provide
clarity.

- Jason

Aug 24 '07 #1
11 1833
Jason wrote:
I've inherited some old C code that I've been tasked to convert to
C++. I've been running into some problems with memory allocation.

First of all, is there any problems using "malloc" in C++? I know
using "new" is preferable, but for now I have to use what is provided.
No, there are no problems with 'malloc', except that it does not
initialise the memory it allocates.
Second, do FILE pointers need to have memory allocated?
FILE pointers are those you obtain from the system by means of the
'fopen' function calls. You need not allocate anything.
My specific problem is this: (all code examples are abbreviated for
clarity)

I have a class

class TObjectDef
{
public:
char *cpFileName;
int iRecordLength;
int iCurrentRecord;
long lRecordCount;
FILE *tpFilePointer
char cpRecBuf[2048];
}

which is initialized

gsPpk = new TObjectDef();
Assuming that 'gsPpk' is declared as a pointer to TObjectDef.
then, much later in the code (about 80k lines later), a float array is
initialized from this structure

(definition
struct DataSegments
{
char caDataId[6];
int iDataCount;
float *fpArr1;
float *fpArr2;
}
)

like so

void vSetFpArray(str uct DataSegments *spDataSeg, float *fpArr1, float
*fpArr2)
{
int iDataCount;
int iDataIndex;

iDataCount = spDataSeg->iDataCount;
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);
I am sure you meant

spDataSeg->fpArr2 =

here, didn't you? Otherwise you assign to the same variable twice,
which means you leak memory and leave 'fpArr2' unchanged.
>
for (iDataIndex = 0; iDataIndex < iDataCount; iDataIndex++)
{
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
Again, those two statements are _exactly_the_sa me_. Did you mean
to do

spDataSeg->fpArr2[iDataIndex] = fpArr2[iDataIndex];

on the second line?
}
return;
}

The function is called like

vSetFpArray(&sD ataSegments[currInd],floatArray1,fl oatArray2);

where the variables are defined as
static DataSegments sDataSegments[512];
float floatArray1[1024];
float floatArray2[1024];

The function above gets called just fine 318 times. On the 319th
iteration, when "malloc" is called, it is overwriting part of the
previously defined class (which is global to this function). The
tpFilePointer goes from being NULL to being "1" after the first
malloc, and "2" after the second. (as in, pointing to memory address
:00000002).
<shrug Impossible to tell what that's due.
Can anyone see any obvious problems with all this that I may have
overlooked? (Besides the obvious problems with global classes and
such.) I apologize if this question didn't make any sense, I'm happy
to provide clarity.
Yes, the obvious problems I've pointed out. The non-obvious are
most likely beyond the posted code.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 24 '07 #2
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:fa******** **@news.datemas .de...
>>[...]
First of all, is there any problems using "malloc" in C++? I know
using "new" is preferable, but for now I have to use what is provided.

No, there are no problems with 'malloc', except that it does not
initialise the memory it allocates.
But it _does_ allocate memory, as in it locks memory on the heap for that
specific pointer?
FILE pointers are those you obtain from the system by means of the
'fopen' function calls. You need not allocate anything.
Thanks, that's what I suspected.
>>[...]
gsPpk = new TObjectDef();

Assuming that 'gsPpk' is declared as a pointer to TObjectDef.
Correct.
>>[...]
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);
spDataSeg->fpArr1 = (float *)malloc(sizeof (float) * iDataCount);

I am sure you meant

spDataSeg->fpArr2 =

here, didn't you? Otherwise you assign to the same variable twice,
which means you leak memory and leave 'fpArr2' unchanged.
Yes, you are correct. I changed the variable names for this example, and
copy/pasted it into the code. Missed updating the second reference, I
apologize for the confusion. The old variable names are part of a
proprietary application, needed to change them for my own job security.
Again, those two statements are _exactly_the_sa me_. Did you mean
to do

spDataSeg->fpArr2[iDataIndex] = fpArr2[iDataIndex];

on the second line?
Again, I apoligize for the confusion.
>The function above gets called just fine 318 times. On the 319th
iteration, when "malloc" is called, it is overwriting part of the
previously defined class (which is global to this function). The
tpFilePointe r goes from being NULL to being "1" after the first
malloc, and "2" after the second. (as in, pointing to memory address
:00000002).

<shrug Impossible to tell what that's due.
Any suggestions on things I could be looking for while debugging? There are
no errors until it gets further down in the code, and an attempt is made to
initialize and use that file pointer.
>Can anyone see any obvious problems with all this that I may have
overlooked? (Besides the obvious problems with global classes and
such.) I apologize if this question didn't make any sense, I'm happy
to provide clarity.

Yes, the obvious problems I've pointed out. The non-obvious are
most likely beyond the posted code.
Besides my typos, everything looks fine? Thanks for your advice, that's
what I needed to know. I am still relatively new to the C++ environment,
being an old Delphi programmer, so outside perspective is always
appreciated.

- Jason
Aug 24 '07 #3
Jason wrote:
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:fa******** **@news.datemas .de...
>>[...]
First of all, is there any problems using "malloc" in C++? I know
using "new" is preferable, but for now I have to use what is
provided.

No, there are no problems with 'malloc', except that it does not
initialise the memory it allocates.

But it _does_ allocate memory, as in it locks memory on the heap for
that specific pointer?
Sure. If you look at some popular implementations of 'new' and
'new[]', you'll see that internally they use 'malloc', actually.
[..]
>>The function above gets called just fine 318 times. On the 319th
iteration, when "malloc" is called, it is overwriting part of the
previously defined class (which is global to this function). The
tpFilePoint er goes from being NULL to being "1" after the first
malloc, and "2" after the second. (as in, pointing to memory
address
00000002).

<shrug Impossible to tell what that's due.

Any suggestions on things I could be looking for while debugging?
If 'malloc' somehow overrides (steps onto) some memore you're still
using for some other object, it could be only two things: the heap
is corrupt (your program writes beyond the bounds of a dynamically
allocated object, thus crossing over to memory that doesn't really
belong to it, OR your "part of previously defined class" was somehow
transferred from under your control and it's now part of the heap
that 'malloc' is free to reuse.

What you should do is to get the tool that would allow you to debug
memory allocations and access. Rational Purify, BoundsChecker, come
to mind.
There are no errors until it gets further down in the code, and an
attempt is made to initialize and use that file pointer.
Memory access troubles are the worst, and if you get them under your
control, you're going to be very happy.
>>Can anyone see any obvious problems with all this that I may have
overlooked? (Besides the obvious problems with global classes and
such.) I apologize if this question didn't make any sense, I'm
happy to provide clarity.

Yes, the obvious problems I've pointed out. The non-obvious are
most likely beyond the posted code.

Besides my typos, everything looks fine? Thanks for your advice,
that's what I needed to know. I am still relatively new to the C++
environment, being an old Delphi programmer, so outside perspective
is always appreciated.
Here is something you might want to consider: do NOT use dynamic
memory allocated directly by you, instead use standard containers.
Switch to using 'std::vector<fl oat>' instead of 'malloc'ed 'float*'.
Easier to debug, for sure.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 24 '07 #4
Jason wrote:
"red floyd" <no*****@here.d udewrote in message
news:wd******** ***********@new ssvr12.news.pro digy.net...
>Also, malloc'ed memory is uninitialized, until you fill it with
something, it's UB to read that memory.

UB?
"Undefined behaviour"

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 24 '07 #5
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:fa******** **@news.datemas .de...
Jason wrote:
>UB?

"Undefined behaviour"
Well that makes a lot more sense than "Undistribu ted Budget".

*sigh*

- Jason
Aug 24 '07 #6
Jason wrote:
I've inherited some old C code that I've been tasked to convert to
C++. I've been running into some problems with memory allocation.

First of all, is there any problems using "malloc" in C++? I know
using "new" is preferable, but for now I have to use what is provided.
As the others have mentioned, malloc() will work for allocating raw
buffers. One difference between C and C++ is that C has automatic
conversion of void pointers to object pointers, while C++ does not.
It's possible that the old code could be written like:

int *p = malloc(8 * sizeof(int));

That won't work in C++. That being said, it's extremely common for C
code to cast the pointer from malloc() anyway, even though it's not
needed and not really a good idea in C, as it can hide a nasty error.

Brian
Aug 24 '07 #7
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:fa******** **@news.datemas .de...
Jason wrote:
>But it _does_ allocate memory, as in it locks memory on the heap for
that specific pointer?

Sure. If you look at some popular implementations of 'new' and
'new[]', you'll see that internally they use 'malloc', actually.
Well that explains why I'm still getting the same error using "new" and
"delete".
If 'malloc' somehow overrides (steps onto) some memore you're still
using for some other object, it could be only two things: the heap
is corrupt (your program writes beyond the bounds of a dynamically
allocated object, thus crossing over to memory that doesn't really
belong to it, OR your "part of previously defined class" was somehow
transferred from under your control and it's now part of the heap
that 'malloc' is free to reuse.
The old code is horrendous, with objects being used before they exist, and
other inappropriate actions. I'm really not surprised that this is
happening, just confused about how to solve it with no *apparent* errors. I
was hoping that this was going to be more of an oversight on my part than
anything. The object that is being overwritten is most likely being
re-initialized somewhere. If I re-allocate an object doing:

gsPpk = new ObjectDef();

then later in the code do

gsPpk = new ObjectDef();

again, what happens? Is the original instance of the object lost and that
memory locked?
What you should do is to get the tool that would allow you to debug
memory allocations and access. Rational Purify, BoundsChecker, come
to mind.
Thanks, I will definitely check into some options.
Memory access troubles are the worst, and if you get them under your
control, you're going to be very happy.
c:\stupidprojec t>del /f /s *.*

would make me happy.
>Besides my typos, everything looks fine? Thanks for your advice,
that's what I needed to know. I am still relatively new to the C++
environment, being an old Delphi programmer, so outside perspective
is always appreciated.

Here is something you might want to consider: do NOT use dynamic
memory allocated directly by you, instead use standard containers.
Switch to using 'std::vector<fl oat>' instead of 'malloc'ed 'float*'.
Easier to debug, for sure.
If only it were that simple. If I could merely do a gloabl search/replace,
my life would be so much simpler.

- Jason
Aug 24 '07 #8
"Default User" <de***********@ yahoo.comwrote in message
news:5j******** *****@mid.indiv idual.net...
As the others have mentioned, malloc() will work for allocating raw
buffers. One difference between C and C++ is that C has automatic
conversion of void pointers to object pointers, while C++ does not.
It's possible that the old code could be written like:

int *p = malloc(8 * sizeof(int));

That won't work in C++. That being said, it's extremely common for C
code to cast the pointer from malloc() anyway, even though it's not
needed and not really a good idea in C, as it can hide a nasty error.
There were a few places in the old code like this, but things like that
throw compilation errors. The code now compiles fine, but I'm getting
memory problems at run-time.

- Jason
Aug 24 '07 #9
Jason wrote:
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:fa******** **@news.datemas .de...
>Jason wrote:
>>But it _does_ allocate memory, as in it locks memory on the heap for
that specific pointer?

Sure. If you look at some popular implementations of 'new' and
'new[]', you'll see that internally they use 'malloc', actually.

Well that explains why I'm still getting the same error using "new"
and "delete".
Make sure you do the right 'delete' -- "delete[]" for arrays.
>If 'malloc' somehow overrides (steps onto) some memore you're still
using for some other object, it could be only two things: the heap
is corrupt (your program writes beyond the bounds of a dynamically
allocated object, thus crossing over to memory that doesn't really
belong to it, OR your "part of previously defined class" was somehow
transferred from under your control and it's now part of the heap
that 'malloc' is free to reuse.

The old code is horrendous, with objects being used before they
exist, and other inappropriate actions. I'm really not surprised
that this is happening, just confused about how to solve it with no
*apparent* errors. I was hoping that this was going to be more of an
oversight on my part than anything. The object that is being
overwritten is most likely being re-initialized somewhere. If I
re-allocate an object doing:
gsPpk = new ObjectDef();

then later in the code do

gsPpk = new ObjectDef();

again, what happens?
Nothing awful, most likely.
Is the original instance of the object lost and
that memory locked?
The original instance is "lost" in terms of gaining access to it, but
the memory is still allocated. This is what's known to be "a memory
leak", since the memory is (and cannot be) deallocated because the
pointer to that memory has been lost when you override the value in
the 'gsPpk'. Unless, of course, somebody holds onto the value of the
pointer, which in itself may be a BAD IDEA(tm).
[..]
>Memory access troubles are the worst, and if you get them under your
control, you're going to be very happy.

c:\stupidprojec t>del /f /s *.*

would make me happy.
I hear you.
>>Besides my typos, everything looks fine? Thanks for your advice,
that's what I needed to know. I am still relatively new to the C++
environment , being an old Delphi programmer, so outside perspective
is always appreciated.

Here is something you might want to consider: do NOT use dynamic
memory allocated directly by you, instead use standard containers.
Switch to using 'std::vector<fl oat>' instead of 'malloc'ed 'float*'.
Easier to debug, for sure.

If only it were that simple. If I could merely do a gloabl
search/replace, my life would be so much simpler.
Refactoring old C code is not much fun. But it's often what you have
to do and it's better done right. That includes stopping the use of
"naked" pointers for arrays and switching to using proper standard
containers. While it looks daunting at first, you will save more time
later if you have done that.

Talk you your boss, ask for an extension of couple of days, back your
project up in a reliable location, then comb those "naked" pointers
out and replace them with vectors. You'll be glad you do.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 24 '07 #10

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

Similar topics

19
683
by: john smith | last post by:
Can someone please explain to me what is happening when I do a malloc(0). This is what I did. int* p = (int*)malloc(0); Then I printed the value of p and of course it was non-null. But has it allocated memory or what?
34
6420
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have started messing around in Plan 9, and that sort of thing is totally no go there :). Is this correct to allocate memory for my struct? It works on my computer, but I'm suspicious that I'm doing it wrong. --
231
23072
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
7
2204
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
20
10738
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
15
2570
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that malloc always returned null at this moment and the program exited (even though if I malloc'ed only 20 bytes or something)... Then I googled for this problem and found something about a memory pool??? Is that standard C? I didn't understand it,...
68
15665
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
40
2558
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd struct? */ Seems to me there is no guarantee it will. /Why Tea
71
19076
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
23
2706
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef struct pxl { double lon, lat;
0
8496
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
8148
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
8338
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
6816
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
6013
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
5475
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
3962
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
4024
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1329
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.