
August 24th, 2007, 05:55 PM
| | | 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(struct 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(&sDataSegments[currInd],floatArray1,floatArray2);
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 | 
August 24th, 2007, 06:15 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
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. Quote: |
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. Quote:
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. Quote:
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(struct 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. Quote:
>
for (iDataIndex = 0; iDataIndex < iDataCount; iDataIndex++)
{
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
spDataSeg->fpArr1[iDataIndex] = fpArr1[iDataIndex];
| Again, those two statements are _exactly_the_same_. Did you mean
to do
spDataSeg->fpArr2[iDataIndex] = fpArr2[iDataIndex];
on the second line? Quote:
}
return;
}
>
The function is called like
>
vSetFpArray(&sDataSegments[currInd],floatArray1,floatArray2);
>
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. Quote:
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 | 
August 24th, 2007, 06:45 PM
| | | Re: malloc problem in C++
"Victor Bazarov" <v.Abazarov@comAcast.netwrote in message
news:fan3ip$713$1@news.datemas.de... Quote: Quote:
>>[...]
>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? Quote:
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. Quote: Quote:
>>[...]
>gsPpk = new TObjectDef();
| >
Assuming that 'gsPpk' is declared as a pointer to TObjectDef.
| Correct. Quote: Quote:
>>[...]
> 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. Quote:
Again, those two statements are _exactly_the_same_. Did you mean
to do
>
spDataSeg->fpArr2[iDataIndex] = fpArr2[iDataIndex];
>
on the second line?
>
| Again, I apoligize for the confusion. Quote: Quote:
>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.
| 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. Quote: Quote:
>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 | 
August 24th, 2007, 06:55 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
"Victor Bazarov" <v.Abazarov@comAcast.netwrote in message
news:fan3ip$713$1@news.datemas.de... Quote: Quote:
>>[...]
>>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. Quote:
[..] Quote: Quote:
>>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.
| >
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. Quote:
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. Quote: Quote: Quote:
>>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<float>' 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 | 
August 24th, 2007, 06:55 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
"red floyd" <no.spam@here.dudewrote in message
news:wdEzi.47520$Um6.44944@newssvr12.news.prodigy. net... Quote:
>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 | 
August 24th, 2007, 07:15 PM
| | | Re: malloc problem in C++
"Victor Bazarov" <v.Abazarov@comAcast.netwrote in message
news:fan5us$ej4$1@news.datemas.de... Quote:
Jason wrote:>
"Undefined behaviour"
>
| Well that makes a lot more sense than "Undistributed Budget".
*sigh*
- Jason | 
August 24th, 2007, 07:15 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
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 | 
August 24th, 2007, 07:15 PM
| | | Re: malloc problem in C++
"Victor Bazarov" <v.Abazarov@comAcast.netwrote in message
news:fan5sq$eba$1@news.datemas.de... Quote:
Jason wrote: Quote:
>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". Quote:
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? Quote:
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. Quote:
Memory access troubles are the worst, and if you get them under your
control, you're going to be very happy.
| c:\stupidproject>del /f /s *.*
would make me happy. Quote: Quote:
>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<float>' 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 | 
August 24th, 2007, 07:15 PM
| | | Re: malloc problem in C++
"Default User" <defaultuserbr@yahoo.comwrote in message
news:5j8l0tF2h69d8U1@mid.individual.net... Quote:
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 | 
August 24th, 2007, 08:05 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
"Victor Bazarov" <v.Abazarov@comAcast.netwrote in message
news:fan5sq$eba$1@news.datemas.de... Quote:
>Jason wrote: Quote:
>>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. Quote: Quote:
>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. Quote:
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). Quote:
[..] Quote:
>Memory access troubles are the worst, and if you get them under your
>control, you're going to be very happy.
| >
c:\stupidproject>del /f /s *.*
>
would make me happy.
| I hear you. Quote: Quote: Quote:
>>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<float>' 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 | 
August 24th, 2007, 09:55 PM
| | | Re: malloc problem in C++
Jason wrote: Quote:
"Default User" <defaultuserbr@yahoo.comwrote in message
news:5j8l0tF2h69d8U1@mid.individual.net... Quote:
>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.
>
| Use whatever memory access tools your platform has to help track these down.
--
Ian Collins. | 
August 27th, 2007, 03:35 PM
| | | Re: malloc problem in C++
"Jason" <us.NOSPAM@jswynn.NOSPAM.comwrote in message
news:46cf1081$0$14043$baae4c71@news.mindlink.net.. . Quote:
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.
>
[snip snip]
| In case anyone was wondering how this turned out, it actually turned out to
be all happening in a totally different part of the code. I also found out
that initializing an object twice causes very undesirable results.
gsFoo = new FooObject;
.....
gsFoo = new FooObject;
It seems that my code was still trying to use the old instance of the object
after this point, which is obviously not a good thing.
Anyways, thanks for all your help.. it's getting there. :-)
- Jason | | Thread Tools | Search this Thread | | | |
Posting Rules
| You may not post new threads You may not post replies You may not post attachments You may not edit your posts HTML code is Off | | | | | | What is Bytes?
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 205,338 network members.
|