473,378 Members | 1,498 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,378 software developers and data experts.

Having a bit of a blonde moment with malloc...

Hi, just need a bit of help!
I know this is a simple question but it's wrecking my head and I end up
just staring at the screen for ages...
I have a multi-source program -myProg1.cpp
-myProg2.cpp
-foo.h
All that happens is that myProg1 passes an int to myProg2 which uses
the int to dynamically allocate memory for an array using malloc()

I've done this before with no problem but not today!!!
Here's the code:

/* myprog1.cpp */
#include <stdio.h>
#include "foo.h"

int maxDepth;

void main(void)
{
int prenum;
printf("\nEnter the size of the word\n");
scanf("%d",&prenum);
maxDepth = prenum + 3;
myfunction();
}

/* myprog2.cpp */

#include <stdio.h>
#include <stdlib.h>

extern int maxDepth;

int * raw;

void myfunction(void) {
int i;
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/
for(i=0;i<4;i++){
raw[i] = i*i;
printf("%d/n",raw[i]);
}
free(raw);
}
/* foo.h */
void myfunction(void);

I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.
I appreciate any help,
Tony

Jan 20 '06 #1
17 1945
>> raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this line*/

You are trying to force the result of malloc into an integer, not a
pointer to an integer.

do (int*)malloc(... and you'll be fine..

Jan 20 '06 #2

dutchgoldtony wrote:
Hi, just need a bit of help!
I know this is a simple question but it's wrecking my head and I end up
just staring at the screen for ages...
I have a multi-source program -myProg1.cpp
-myProg2.cpp
-foo.h
All that happens is that myProg1 passes an int to myProg2 which uses
the int to dynamically allocate memory for an array using malloc()

I've done this before with no problem but not today!!!
Here's the code:

/* myprog1.cpp */
#include <stdio.h>
#include "foo.h"

int maxDepth;

void main(void)
{
int prenum;
printf("\nEnter the size of the word\n");
scanf("%d",&prenum);
maxDepth = prenum + 3;
myfunction();
}

/* myprog2.cpp */

#include <stdio.h>
#include <stdlib.h>

extern int maxDepth;

int * raw;

void myfunction(void) {
int i;
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/
for(i=0;i<4;i++){
raw[i] = i*i;
printf("%d/n",raw[i]);
}
free(raw);
}
/* foo.h */
void myfunction(void);

I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.
I appreciate any help,
Tony


Two issues:
1) You are casting the pointer to an integer, you don't want any cast
at
all here in "C" in this case. raw is an int*, why are you casting
the void* returned by malloc to an int?

2) You are apparently compiling as C++. If you mean to be doing that,
you should
ask in comp.lang.c++. <OT> you should probably use new if so,
or if malloc is wanted you need to cast to (int*). </OT>

A better paradigm would be

raw = malloc(maxDepth * sizeof *raw);

And you should check that malloc didn't return NULL.

-David

Jan 20 '06 #3
dutchgoldtony wrote:

Hi, just need a bit of help! [...] int * raw; [...] raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/ [...] I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'

[...]

Well, you're writing in C++, not C, so technically you're off-topic for
this group.

However, the above two lines are just as invalid in C as in C++, so here
goes...

What type is "raw"?
What are you casting the return of malloc() to?
What type conversion is the compiler complaining about?

And, since this is clc and not clc++...

"void main(void)" is invalid in C. (I don't know about C++.)

Don't cast the return value from malloc in C, as this will mask
errors related to missing header files. (However, I understand
that the cast is needed in C++.)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Jan 20 '06 #4
Thanks all for the help,
I actually hadn't meant to be compiling in C++, just that the compiler
I'm using creates both C and C++ source files as .cpp. Definitely no
intention to post in the wrong location, didn't realise I was using any
C++ functionality, just C.
I was trying to just dynamically create an array of ints (size
maxDepth) in C.
Is void main (void) illegal? Didn't realise... Should I be returning
something to indicate error or successful completion?

Sorry for any daft mistakes / assertions, we all have to start
somewhere!
Cheers,
Tony

Jan 20 '06 #5
How about if I was to do the same with a struct i.e. how might I
dynamically do the following?
struct node{
int state;
int status ;
struct node* connectedNodes[2];
int transitionCost[2];
};
struct node n[4][maxDepth];

Jan 20 '06 #6

dutchgoldtony wrote:
[snip]
Is void main (void) illegal? Didn't realise... Should I be returning
something to indicate error or successful completion?

According to the C language standard, main() must return an int. The
two standard definitions for main are:

int main(void)
int main(int argc, char **argv)

An implementation may provide additional prototypes for main(), but the
two above will work anywhere.

Return one of EXIT_SUCCESS or EXIT_FAILURE.
Sorry for any daft mistakes / assertions, we all have to start
somewhere!
Cheers,
Tony


Jan 20 '06 #7
"John Bode" <jo*******@my-deja.com> writes:
According to the C language standard, main() must return an int. The
two standard definitions for main are:

int main(void)
int main(int argc, char **argv)

An implementation may provide additional prototypes for main(), but the
two above will work anywhere.


A conforming hosted implementation does not provide any prototype for
main() at all (§5.1.2.2.1).

DES
--
Dag-Erling Smørgrav - de*@des.no
Jan 20 '06 #8

dutchgoldtony wrote:
Hi, just need a bit of help!
I know this is a simple question but it's wrecking my head and I end up
just staring at the screen for ages...
I have a multi-source program -myProg1.cpp
-myProg2.cpp
-foo.h
All that happens is that myProg1 passes an int to myProg2 which uses
the int to dynamically allocate memory for an array using malloc()

I've done this before with no problem but not today!!!
Here's the code:

/* myprog1.cpp */
#include <stdio.h>
#include "foo.h"

int maxDepth;

void main(void)
{
that's
int main (void)
int prenum;
printf("\nEnter the size of the word\n");
scanf("%d",&prenum);
maxDepth = prenum + 3;
myfunction();
}

/* myprog2.cpp */

#include <stdio.h>
#include <stdlib.h>

extern int maxDepth;

int * raw;

void myfunction(void) {
int i;
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/
for(i=0;i<4;i++){
raw[i] = i*i;
printf("%d/n",raw[i]);
}
free(raw);
}
/* foo.h */
void myfunction(void);

I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.


compiler's often say what they mean. In this case malloc() returns
a void* (not's a *pointer*) which you cast to an int (*not* a
pointer!).
NEVER cast the return value of malloc() in a C program (you may be
using C++). You then assign this int to an int*. And what does the
compiler say?

All that stuff about reinterpret_cast indicates you are using a C++
compiler. If you want to compile a C program use a C compiler. If
you want to compile a C++ program ask in comp.lang.c++. They
will probably tell you not to use malloc() at all.
--
Nick Keighley

Jan 20 '06 #9
On 2006-01-20, John Bode <jo*******@my-deja.com> wrote:

dutchgoldtony wrote:
[snip]
Is void main (void) illegal? Didn't realise... Should I be returning
something to indicate error or successful completion?


According to the C language standard, main() must return an int. The
two standard definitions for main are:

int main(void)
int main(int argc, char **argv)

An implementation may provide additional prototypes for main(), but the
two above will work anywhere.

Return one of EXIT_SUCCESS or EXIT_FAILURE.


Or zero.
Jan 20 '06 #10
dutchgoldtony wrote:
Hi, just need a bit of help!
I know this is a simple question but it's wrecking my head and I end up
just staring at the screen for ages...
I have a multi-source program -myProg1.cpp
-myProg2.cpp
-foo.h
Because of your filenames, I would strongly suspect that you are trying
to write C++ programs (C++ and C are different languages; C++ questions
go to comp.lang.c++), except that void main(void) is illegal in both C and C++.

int * raw;

void myfunction(void) {
int i;
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/
casting the void * to int and then trying to assign this int to an int *
is not only pointless but has no defined meaning in C or C++.

In C, casting at all is silly, serves no purpose except to hide your own
errors.
raw = malloc(maxDepth * sizeof *raw);
is the preferred idiom.
C++ is off-topic here, but because of other 'features' of C++ a cast is
required, and that cast should be to int *, not int.

I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast


This is obviously a C++ error message. This confirms two things:
1) you should be posting to comp.lang.c++
2) your diagnostics are not set correctly, or you would have been warned
about the BullShildt 'void' return type for main.
Jan 20 '06 #11
Philip Soeberg wrote:
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this line*/

You are trying to force the result of malloc into an integer, not a
pointer to an integer.

do (int*)malloc(... and you'll be fine..


Do *not* do that. If you are indeed trying to write C, then don't
follow this piece of broken C++ 'wisdom.' Needing to cast the return
value from malloc in a C program always indicates an error.
Jan 20 '06 #12
dutchgoldtony wrote:
.... snip ...
I've done this before with no problem but not today!!!
Here's the code:

/* myprog1.cpp */


C source programs usually have the extension .c. .cpp usually
causes a compiler to assume it to be C++ source, which is a
different language and nothing to do with us here.

C++ forces the very poor technique (in C) of casting void* ptrs.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 21 '06 #13
dutchgoldtony wrote:

I actually hadn't meant to be compiling in C++, just that the
compiler I'm using creates both C and C++ source files as .cpp.
Definitely no intention to post in the wrong location, didn't
realise I was using any C++ functionality, just C.


Compilers don't create C (or C++) source files. You are probably
misusing somebodies IDE (Integrated Development Environment). It
is generally easier to edit and then compile (or make) from the
command line. If you are using Microsoft VC etc. you can set it up
properly for C. Microsoft loves to obscure everything.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 21 '06 #14
Thanks very much for all the help, looks like I need to get myself a
reference book or two...

Jan 21 '06 #15
dutchgoldtony a écrit :
I have a multi-source program -myProg1.cpp
-myProg2.cpp
-foo.h
Starts badly. If you intent to write in C, you should use a C compiler.
Hence, the file-extension should be .c and not .cpp or .C.
All that happens is that myProg1 passes an int to myProg2 which uses
the int to dynamically allocate memory for an array using malloc()

I've done this before with no problem but not today!!!
Here's the code:

/* myprog1.cpp */
#include <stdio.h>
#include "foo.h"

int maxDepth;
A global in the main compile unit ? Sounds weird... Well, it's more a
'Good Design Policy' than a C-issue, but this module is not supposed to
export anything but main().

BTW, do you really need this global ?
void main(void)
This is incorrect. main() returns int. always.
{
int prenum;
printf("\nEnter the size of the word\n");
scanf("%d",&prenum);
Incorrect use of scanf().
- missing return test
- missing purge on error.

scanf() is a hard-to-use function. It is recommended to use fgets() and
strtol(), for instance.
maxDepth = prenum + 3;
myfunction();
Huh, how is 'myfunction()' aware if the input value ? Sounds like a
design issue here... Let me guess, a global variable ? I can't believe
it... What about a simple parameter ?

myfunction(maxDepth);

with

void myfunction(int n);
}

/* myprog2.cpp */

#include <stdio.h>
#include <stdlib.h>

extern int maxDepth;
weird and ugly...
int * raw;
OMG, a global, again ?
void myfunction(void) {
int i;
raw = (int)malloc(maxDepth * sizeof(int)); /*Error points to this
line*/
What the heck is this (int) made for ?

- The cast was not required since 1989
- If it was (old C compiler), it would have been (int*) according to the
pointer's type.
for(i=0;i<4;i++){
Why '4' ? What is the magic in this value ?
raw[i] = i*i;
printf("%d/n",raw[i]);
}
free(raw);
That's cute, but the whole malloc() thing seems meaningless.

int i;
for (i = 0; i < 4; i++)
{
printf ("%d/n", i * i);
}
}
/* foo.h */
void myfunction(void); I keep on getting the following error:
f:\project\test2\encoder.cpp(18) : error C2440: '=' : cannot convert
from 'int' to 'int *'
Yes, this is exactly what you are attempting to do, and it's wrong.
Conversion from integral type to pointer type requires
reinterpret_cast, C-style cast or function-style cast


Sounds very much that your compiler is not a C-compiler (probably due to
the bad choice of the file extensions).

--
A+

Emmanuel Delahaye
Jan 21 '06 #16
On 20 Jan 2006 07:12:24 -0800, "dutchgoldtony"
<du***********@gmail.com> wrote:

(without any context; please see http://cfaj.freeshell.org/google/ )
Thanks all for the help,
I actually hadn't meant to be compiling in C++, just that the compiler
I'm using creates both C and C++ source files as .cpp. Definitely no
#if OFFTOPC == M$VS
Only by default. If you create from the IDE with "File New" just type
the filename with a .c extension, and it will be treated and compiled
as C. If you also tick "Disable language extensions" (IIRC) in Project
Settings, either for the whole project or for particular source
file(s), M$VC does as good a job as most of being standard-conforming.
(Ignore most of the Windowsian advice in the help, though.)

For an existing file AFAICT you can't actually rename in the IDE;
instead, if you don't have attribute settings you need to keep, delete
the file from your project (which doesn't delete the actual file),.
rename the file in explorer or a "DOS" (command) window, and add the
renamed file back into your project. If you do need to keep
attributes, you have to exit the IDE, rename the file and edit the
..dsp manually (and carefully!), and restart.

Alternatively you can override the language setting so even a file
named .cpp compiles as C (or .c as C++) but this is (a) confusing and
(b) too easy to muck up later.
#endif
intention to post in the wrong location, didn't realise I was using any
C++ functionality, just C. I was trying to just dynamically create an array of ints (size
maxDepth) in C.
Is void main (void) illegal? Didn't realise... Should I be returning
something to indicate error or successful completion?

Yes. In fact 'void main' is even _more_ illlegal in C++ than in C; in
C it is simply left undefined by the standard but need not be
diagnosed, as described elsethread, while in C++ it violates a
nonwaived 'shall' and (thus) must be diagnosed by the compiler.

In C++(98) and C99 if you reach the end of main() without specifying a
return value, the exit status is 0, which is "successful". But it is
better style, as well as portable to C89, to specify this explicitly.

In standard C there is only one error value you can portably exit
with: EXIT_FAILURE defined in <stdlib.h>. On many systems, including
Windows, you can return a larger variety of integer values, which may
or may not be useful depending on what your program is and how it is
(to be) used.

- David.Thompson1 at worldnet.att.net
Feb 6 '06 #17
Dave Thompson <da*************@worldnet.att.net> writes:
[...]
Yes. In fact 'void main' is even _more_ illlegal in C++ than in C; in
C it is simply left undefined by the standard but need not be
diagnosed, as described elsethread, while in C++ it violates a
nonwaived 'shall' and (thus) must be diagnosed by the compiler.


In C99, the main() function "shall be defined with a return type of
int and with no parameters [...] or with two parameters ([...]argc and
argv[...]) ... or in some other implementation-defined manner."

"void main(void)" is legal *if* the implementation defines it as legal
(which means it must be explicitly documented).

If the implementation doesn't document this form, then "void main(void)"
violates a "shall" outside a constraint, which means it's undefined
behavior.

But all you really need to know is one simple rule: don't do that.

--
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.
Feb 6 '06 #18

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

Similar topics

12
by: LongBow | last post by:
Hello all, From doing a google serach in the newsgroups I found out that a string can't be returned from a function, but using a char* I should be able to do it. I have spent most of the day...
14
by: Joseph | last post by:
I am trying to create a function that allocates memory for the matrix through a function; like the code below. However, this does not seem to work since I believe that the scope of the memory...
7
by: | last post by:
I fail to understand why that the memory allocated in the void create(int **matrix) does not remain. I passed the address of matrix so shouldn't it still have the allocated memory when it returns...
16
by: Fronsac | last post by:
Hi, I've been asked in a job interview how to make C code look like C++ code, and honestly I didn't know what to answer because I have never really done a lot of C. Now, I've been searching around...
2
by: yogeshmk | last post by:
I've a problem with array values getting lost in function call. Here is the flow. ===========driver.c================= /* this is just a driver to test a library wrapper * originally it's a...
38
by: sam_cit | last post by:
Hi, I have the following Struct, Struct Sample { int i; char *p; };
6
by: itsolution | last post by:
Hi folks, Could you shed some light on this issue? my program is running on Freebsd as a daemon. When user sends a request, it forks itself and lets its child process handles the request....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...

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.