473,799 Members | 3,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(i nt) * steps);

...

}

So far so good.

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

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

value = compute(steps, 1);
printf("\n%5.5l f", 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_arra y);
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 5490
Schizoid Man <sc***@sf.comwr ites:
>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(i nt) * steps);
^^^^^^^^^^^
Possibly: (sizeof *price_array)

?

--
Chris.
Jul 30 '06 #2
Schizoid Man (in ea**********@ge raldo.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(i nt) * steps);
|
| ...
|
| }
|
| So far so good.
|
| Now in my main method, I invoke this function twice:
|
| value = compute(steps, 0);
| printf("\n%5.5l f", value);
|
| value = compute(steps, 1);
| printf("\n%5.5l f", value);

<snipperectom y>

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(unsigne d,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(i nt) * 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.comwr ote:
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(i nt) * 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**********@ge raldo.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(i nt) * steps);
|
| ...
|
| }
|
| So far so good.
|
| Now in my main method, I invoke this function twice:
|
| value = compute(steps, 0);
| printf("\n%5.5l f", value);
|
| value = compute(steps, 1);
| printf("\n%5.5l f", value);

<snipperectom y>

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(unsigne d,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(i nt) * 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(i nt) * 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

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

Similar topics

13
4123
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 dynamic array of characters int length; //number of characters } String;
4
9021
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, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if I had C / \ B D
3
647
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 level pagetable. Thank you. struct _PageTable { struct _PageTable **PageArray; unsigned int *FrameArray;
6
2007
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 REALLOC that on my pc at times it produces error. Someone can help me for this error? Thank you /*Inclusione librerie*/
2
1817
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 called the function wordcount, and then the function did everything including printing out the results. That worked. Now I want to make the function return an array of pointers to struct palabra so the calling function can manage the data as it...
5
1528
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, char *textFilePtr) { FILE *ifp; char *text; char txtFile;
1
1888
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 to instantiate an arbitrary number of arrays of arbitrary size in function_a, copy the pointers, store the data, and free any unused memory. My basic structure is as follows:
0
6548
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 /new_file/prob1.rec started. Please wait.... In while loop of request searching *** glibc detected *** ./a.out: free(): invalid next size (normal): 0x099da890 *** ======= Backtrace: ========= /lib/libc.so.6
3
2977
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 pass its first block pointer inside the structure Array to Array ->first and the last block pointer inside the structure Array to Array ->last.So i can manipulate the double linked list as a dynamic array. The cells of this dynamic array are...
4
1581
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 filename to a function, and have it pass back an array containing the database contents, and some parameters telling me the dimensions of the array. I've succeeded in getting my function to read in the dbf file, and it returns the dimensions of...
0
10491
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...
0
10268
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10247
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
10031
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
6809
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
5467
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
5593
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.