473,386 Members | 1,835 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Help with malloc()

Hi,

I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer value:

double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);

...

}

So far so good.

Now in my main method, I invoke this function twice:

value = compute(steps, 0);
printf("\n%5.5lf", value);

value = compute(steps, 1);
printf("\n%5.5lf", value);
I get a correct answer for the first time it is invoked, but I get the
following error when the function is invoked the second time (i.e
typeopt = 1): Unhandled exception at 0x00411816: 0xC0000005: Access
violation writing location 0x00000000.

I then go back to the compute method and put a free(price_array);
statement at the end of the method.

I then get the following message:

HEAP: Heap block at 00355870 modified at 0035606C past requested size of
7f4 Windows has triggered a breakpoint. This may be due to a corruption
of the heap, and indicates a bug in or any of the DLLs it has loaded.
The output window may have more diagnostic information.

I would really appreciate any help at all.

Thanks in advance,
Schiz

Jul 30 '06 #1
11 5450
Schizoid Man <sc***@sf.comwrites:
>I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer value:
>double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);
^^^^^^^^^^^
Possibly: (sizeof *price_array)

?

--
Chris.
Jul 30 '06 #2
Schizoid Man (in ea**********@geraldo.cc.utexas.edu) said:

| Hi,
|
| I have a function in which I am reading in an integer value, and
| dynamically creating an array of type double and size of the
| integer value:
|
| double compute(int steps, int typeopt)
| {
| double *price_array;
|
| price_array = (double *) malloc(sizeof(int) * steps);
|
| ...
|
| }
|
| So far so good.
|
| Now in my main method, I invoke this function twice:
|
| value = compute(steps, 0);
| printf("\n%5.5lf", value);
|
| value = compute(steps, 1);
| printf("\n%5.5lf", value);

<snipperectomy>

You haven't really provided enough info to allow a definitive answer.
From what you have provided, I'd suggest:

#include <stdio.h>
#include <stdlib.h>
double compute(unsigned,int);

double *price_array;
price_array = malloc(steps * (sizeof (double)));

Note addition of stdlib.h header and discard of cast. My prototype and
alteration of the statement in which you invoke malloc() makes
(possibly incorrect) assumptions as to how you intend to use the steps
variable; but at that point negative values seem inappropriate.

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto
Jul 30 '06 #3
Schizoid Man wrote:
Hi,

I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer
value:

double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);

...

}

So far so good.
So far NOT so good. You have the wrong type with the sizeof operator.
If double is a different size than int, you won't have the right amount
allocated.

Get rid of the cast, and change the allocation to:

price_array = malloc(steps * sizeof *price_array);
That way you can't screw up the type.
Jul 30 '06 #4
On 2006-07-30, Schizoid Man <sc***@sf.comwrote:
Hi,

I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer value:

double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);
double *price_array = malloc (sizeof *price_array * steps);
if (!price_array)
return (double) -1;

Will fix all of the above problems. What were you doing with sizeof (int)?

--
Andrew Poelstra <website down>
To reach my email, use <email also down>
New server ETA: 42
Jul 30 '06 #5
Morris Dovey wrote:
Schizoid Man (in ea**********@geraldo.cc.utexas.edu) said:

| Hi,
|
| I have a function in which I am reading in an integer value, and
| dynamically creating an array of type double and size of the
| integer value:
|
| double compute(int steps, int typeopt)
| {
| double *price_array;
|
| price_array = (double *) malloc(sizeof(int) * steps);
|
| ...
|
| }
|
| So far so good.
|
| Now in my main method, I invoke this function twice:
|
| value = compute(steps, 0);
| printf("\n%5.5lf", value);
|
| value = compute(steps, 1);
| printf("\n%5.5lf", value);

<snipperectomy>

You haven't really provided enough info to allow a definitive answer.
From what you have provided, I'd suggest:

#include <stdio.h>
#include <stdlib.h>
double compute(unsigned,int);

double *price_array;
price_array = malloc(steps * (sizeof (double)));

Note addition of stdlib.h header and discard of cast. My prototype and
alteration of the statement in which you invoke malloc() makes
(possibly incorrect) assumptions as to how you intend to use the steps
variable; but at that point negative values seem inappropriate.
Hi Morris,

I was already including stdlib.h, but your suggestion did help me out.
If I discard the cast then I get the following error:

error C2440: '=' : cannot convert from 'void *' to 'double *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast

However, if I use the cast then the method works perfectly. Thanks for
the help.
Jul 30 '06 #6
Schizoid Man said:

<snip>
>
I was already including stdlib.h, but your suggestion did help me out.
If I discard the cast then I get the following error:

error C2440: '=' : cannot convert from 'void *' to 'double *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
Then I strongly recommend that you either rename your file from foo.cpp to
foo.c, or ask in comp.lang.c++ in future.

C and C++ are different languages, with different rules. Asking in a C group
about a C++ program doesn't make much sense.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 30 '06 #7
Default User wrote:
Schizoid Man wrote:

>>Hi,

I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer
value:

double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);

...

}

So far so good.


So far NOT so good. You have the wrong type with the sizeof operator.
If double is a different size than int, you won't have the right amount
allocated.

Get rid of the cast, and change the allocation to:

price_array = malloc(steps * sizeof *price_array);
That way you can't screw up the type.
Hi,

I changed the allocation from int to double and that solved my problem.
Removing the cast however gave me a compile error (reported above).

Thanks.
Jul 30 '06 #8
Schizoid Man wrote:
Default User wrote:
>Schizoid Man wrote:

>>Hi,

I have a function in which I am reading in an integer value, and
dynamically creating an array of type double and size of the integer
value:

double compute(int steps, int typeopt)
{
double *price_array;

price_array = (double *) malloc(sizeof(int) * steps);

...

}

So far so good.


So far NOT so good. You have the wrong type with the sizeof operator.
If double is a different size than int, you won't have the right amount
allocated.

Get rid of the cast, and change the allocation to:

price_array = malloc(steps * sizeof *price_array);
That way you can't screw up the type.

Hi,

I changed the allocation from int to double and that solved my problem.
Removing the cast however gave me a compile error (reported above).

Thanks.
Have you

#include <stdlib.h>

?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jul 30 '06 #9
Schizoid Man wrote:
I was already including stdlib.h, but your suggestion did help me out.
If I discard the cast then I get the following error:

error C2440: '=' : cannot convert from 'void *' to 'double *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
You are not using a C compiler. You may have a product that claims to
contain both a C compiler and a C++ compiler. Your documentation should
tell you how to invoke it as a C compiler. Should you not wish to do
that, then your questions should be directed to <news:comp.lang.c++>.

Jul 30 '06 #10
Schizoid Man <sc***@sf.comwrites:
[...]
I was already including stdlib.h, but your suggestion did help me
out. If I discard the cast then I get the following error:

error C2440: '=' : cannot convert from 'void *' to 'double *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast

However, if I use the cast then the method works perfectly. Thanks for
the help.
An implicit conversion from void* to double* (or to any
pointer-to-object type) is perfectly legal in C. The most likely
explanation for the error message is that you're using a C++ compiler.

If you have questions about C++, you'll need to ask in comp.lang.c++,
<OT>and you should probably be using new rather than malloc()</OT>.
If you intend your code to be valid C, use a C compiler.

Casting the result of malloc() is required in C++, and strongly *not*
recommended in C. (Some people may post followups here saying that
you should cast the result of malloc() in C; except in some very
narrow circumstances, they're wrong, for reasons that have been
explained here many times.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 30 '06 #11
Richard Heathfield wrote:
Schizoid Man said:

<snip>
>I was already including stdlib.h, but your suggestion did help me out.
If I discard the cast then I get the following error:

error C2440: '=' : cannot convert from 'void *' to 'double *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast

Then I strongly recommend that you either rename your file from foo.cpp to
foo.c, or ask in comp.lang.c++ in future.

C and C++ are different languages, with different rules. Asking in a C group
about a C++ program doesn't make much sense.
Hi Richard, Martin, Keith,

You're all absolutely right - I am using Microsoft Visual C++. I did
know that an implicit conversion from void to double is legal, so I was
wondering why I get this error without the cast.

Renaming it to .c should do the trick.

Thanks for the help, and sorry for the bother.
Jul 30 '06 #12

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

Similar topics

13
by: na1paj | last post by:
here's a simple linked list program. the DeleteNode function is producing an infinit loop i think, but i can't figure out where.. #include <stdio.h> typedef struct { char *str; //str is a...
4
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working,...
3
by: Robert Rota | last post by:
Need help figuring out why my program core dumps and if I have the structures right. If you are interested in helping me I can send you a copy of the code. The program is supposed to mimic a 3...
6
by: TC | last post by:
Hi. I write a program in c language that read a text file and extrapolate the word. for all word the program calculate the number of the times that word is present in the text. The problem is the...
2
by: leo2100 | last post by:
Hi, I need help with this program. The program is supposed to take a text file and identify the words in it, then it should print them and count how many times a word is repeated. At first main...
5
by: totoro2468 | last post by:
Here is a code I am writing. I keep geting segmentation fault. I'm not sure what i'm doing wrong. Can you explain it to me in PLAIN ENGLISH?? void ReadString (char *filename, int *lengthPtr,...
1
by: Kevin | last post by:
Hi all, I clearly have an issue with some pointers, structures, and memory allocation. Its probably pritty basic, but I'm a little stuck. Any help would be greatly appreciated. I'd like...
0
by: shrik | last post by:
I have following error : Total giant files in replay configuration file are : File name : /new_file/prob1.rec Given file /new_file/prob1.rec is successfully verified. Splitting for giant file...
3
by: dreiko466 | last post by:
(sorry about my english...) I am a newbie in C (3 month expierience) I have wrote a simple test programm in VS2005, what i do wrong?Please... In this programm i create a double linked list.Then ...
4
by: Paul David Buchan | last post by:
Hello, I'm attempting to write a program to read in database files (.dbf). When I do it all as a single procedure in main, everything works. However, what I really want, is to pass the database...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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,...

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.