473,467 Members | 1,992 Online
Bytes | Software Development & Data Engineering Community
Create 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(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

Aug 24 '07 #1
11 1817
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(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.
>
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?
}
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.
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.********@comAcast.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_same_. 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
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.
>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.********@comAcast.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
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.
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<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
Aug 24 '07 #4
Jason wrote:
"red floyd" <no*****@here.dudewrote in message
news:wd*******************@newssvr12.news.prodigy. 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.********@comAcast.netwrote in message
news:fa**********@news.datemas.de...
Jason wrote:
>UB?

"Undefined behaviour"
Well that makes a lot more sense than "Undistributed 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.********@comAcast.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:\stupidproject>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<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
Aug 24 '07 #8
"Default User" <de***********@yahoo.comwrote in message
news:5j*************@mid.individual.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.********@comAcast.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:\stupidproject>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<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
Aug 24 '07 #10
Jason wrote:
"Default User" <de***********@yahoo.comwrote in message
news:5j*************@mid.individual.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.
Use whatever memory access tools your platform has to help track these down.

--
Ian Collins.
Aug 24 '07 #11
"Jason" <us*******@jswynn.NOSPAM.comwrote in message
news:46***********************@news.mindlink.net.. .
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
Aug 27 '07 #12

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

Similar topics

19
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...
34
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...
231
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...
7
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...
20
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
15
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...
68
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;...
40
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...
71
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...
23
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
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: 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...

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.