By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,234 Members | 1,896 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,234 IT Pros & Developers. It's quick & easy.

Dynamic arrays

P: n/a
Hi,

I'm trying to use a dynamic array but for some reason it won't work. This is
my code :

int *test;
int numElements = 2;

test = (int *) malloc (numElements * sizeof(int));
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here
so it's ok I guess
test[0] = 10; // <- CRASH!
printf( "test= %d\n",test[0] );

I copied it from the internet and it seems that they all do it this way?
Then why won't this work? My computer sure has enough for 2 integers...

Greetings,
Rick
Nov 13 '05 #1
Share this Question
Share on Google+
20 Replies


P: n/a
Rick wrote:
I'm trying to use a dynamic array but for some reason it won't work. This is
my code :

int *test;
int numElements = 2;

test = (int *) malloc (numElements * sizeof(int));
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here

^
Hur, hur!

You want ==.

Jirka

Nov 13 '05 #2

P: n/a
"Rick" <as******@hotmail.com> wrote:
Hi,

I'm trying to use a dynamic array but for some reason it won't work. This is
my code :
It's certainly not, it won't even compile.

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

int main(void)
{ int *test;
int numElements = 2;

test = (int *) malloc (numElements * sizeof(int)); ^ spurious cast, you'd better write:

test = malloc ( numElements * sizeof *test );
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here ^ you assign NULL to test here
so it's ok I guess No, you want:

if ( test == NULL )
{
printf("Can't allocate\n");
return EXIT_FAILURE;
}
test[0] = 10; // <- CRASH!
It's not surprising for NULL[0] = 10; to crash. You invoked undefined
behaviour.
printf( "test= %d\n",test[0] );
return EXIT_SUCCESS;
}
I copied it from the internet and it seems that they all do it this way? No, fortunately not.
Then why won't this work? My computer sure has enough for 2 integers...

See above.

HTH
Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #3

P: n/a
Jirka Klaue wrote:
Rick wrote:
I'm trying to use a dynamic array but for some reason it won't work.
This is
my code :

int *test;
int numElements = 2;

test = (int *) malloc (numElements * sizeof(int));
if (test= NULL) printf("Can't allocate\n"); // Nothing happens here


^
Hur, hur!

You want ==.


To OP.
That's why many programmers prefer to write:
if (NULL==test) {
/* ... */
}
To catch the error at compile time.

e.j.s.

--
The white zone is for loading and unloading only.
(Frank Zappa)

Nov 13 '05 #4

P: n/a
Ok, ok, I quickly typed it over. ( s = NULL ) is stupid indeed but in the
real code there are really 2 == :) And no, although there's a bug it does
compile. But look, an exact copy now :

int *da;
int numElements = 2;

da = (int *) malloc (numElements * sizeof(int));
if (da== NULL) printf("damn\n");
da[0] = 10; // The same problem
printf( "test= %d\n",da[0] );

Also tried without the == null line, just for sure, but it doesn't work
neither. I also tried it without (int *)but it keeps crashing.

Greetings,
Rick
Nov 13 '05 #5

P: n/a


Rick wrote:
Ok, ok, I quickly typed it over. ( s = NULL ) is stupid indeed but in the
real code there are really 2 == :) And no, although there's a bug it does
compile. But look, an exact copy now :

int *da;
int numElements = 2;

da = (int *) malloc (numElements * sizeof(int));
if (da== NULL) printf("damn\n");
da[0] = 10; // The same problem
printf( "test= %d\n",da[0] );

Also tried without the == null line, just for sure, but it doesn't work
neither. I also tried it without (int *)but it keeps crashing.


You have a flaw. You should not simply print a message
if the allocation failed and then continue on as if it was
successful. You need and if-else or an exit.

Try this and see if this crashes:

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

int main(void)
{
int *da;
int numElements = 2;

da = malloc(numElements * sizeof(int));
if (da == NULL) printf("damn\n");
else
{
da[0] = 10;
printf( "test= %d\n",da[0] );
free(da);
}
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #6

P: n/a
Very True, but it doesn't solve the problem...

Greetings,
Rick
Nov 13 '05 #7

P: n/a
"sellountos euripides" <se********@mech.upatras.gr> wrote in message
news:bn**********@nic.grnet.gr...
if (test= NULL) printf("Can't allocate\n");

^
Hur, hur!

You want ==.


To OP.
That's why many programmers prefer to write:
if (NULL==test) {
/* ... */
}
To catch the error at compile time.


I prefer to increase the warning level from my compiler, which also sets off
an alarm bell in this type of situation:

int i, j;
/* ... */
if (i = /* whoops! */ j) { /* ... */ }

Alex
Nov 13 '05 #8

P: n/a
Ow, Al, I tried you code (thanks for that) in the main but it still crashes.
What the heck is going on? Even my drunken brain can store 2 integers. It's
just a normal pc. Maybe it are some settings in the old Borland C++??

Greetings,
Rick
Nov 13 '05 #9

P: n/a
Wait! I talk too fast. It does work now, after including #include <stdlib.h>
as well. Are their more versions of malloc or something? The compiler didn't
say anything.

Thanks!
Rick
Nov 13 '05 #10

P: n/a
"Rick" <as******@hotmail.com> wrote:
Ok, ok, I quickly typed it over. ( s = NULL ) is stupid indeed but in the
real code there are really 2 == :) And no, although there's a bug it does
compile. But look, an exact copy now :

int *da;
int numElements = 2;

da = (int *) malloc (numElements * sizeof(int));
if (da== NULL) printf("damn\n");
da[0] = 10; // The same problem
printf( "test= %d\n",da[0] );


Sorry, but your code confuses my compiler:

4: conflicting types for `da'
1: previous declaration of `da'
4: warning: implicit declaration of function `malloc'
4: warning: initialization makes integer from pointer without a cast
4: initializer element is not constant
4: warning: data definition has no type or storage class
5: parse error before "if"
6: warning: type defaults to `int' in declaration of `da'
6: conflicting types for `da'
4: previous declaration of `da'
6: invalid initializer
6: warning: data definition has no type or storage class
7: parse error before string constant
7: warning: type defaults to `int' in declaration of `printf'
7: warning: conflicting types for built-in function `printf'
7: warning: data definition has no type or storage class

Please post a compilable version of your code.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #11

P: n/a
Strange you compiler doesn't take it. Well, maybe it's because of my very
old Borland version. But it's fixed now, the only thing I forgot the whole
time was including stdlib :)

Greetings,
Rick
Nov 13 '05 #12

P: n/a
"Rick" <as******@hotmail.com> wrote:
Wait! I talk too fast. It does work now, after including #include <stdlib.h>
as well. Are their more versions of malloc or something? The compiler didn't
say anything.


You just dicovered the reasons why it's usually bad practice to cast the
return value of malloc (it may hide the fact that you forgot to include
stdlib.h), and why it's good practice to turn up the warning level of
your compiler to maxinmum and treat warnings as errors.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #13

P: n/a
"Rick" <as******@hotmail.com> wrote:
Strange you compiler doesn't take it. Well, maybe it's because of my very
old Borland version. But it's fixed now, the only thing I forgot the whole
time was including stdlib :)


Plus including stdio.h, plus wrapping your code in a main function, plus
casting the return value of malloc, plus failing to pump up your
compilers warning level.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #14

P: n/a
Do you have magic powers? How do you know I forgot all that stuff? I only
gave a piece of the code, not the complete thing. Anyway, everybody thanks
for helping!

Greetings,
Rick
Nov 13 '05 #15

P: n/a
"Rick" <as******@hotmail.com> wrote:
Do you have magic powers? Not yet, but I've got an ACME Crystal Ball [TM]. ;-)
How do you know I forgot all that stuff? I only
gave a piece of the code, not the complete thing. That was the main (sic) problem.
Anyway, everybody thanks
for helping!

You're welcome.

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #16

P: n/a
In <3f***********************@news.xs4all.nl> "Rick" <as******@hotmail.com> writes:
Wait! I talk too fast. It does work now, after including #include <stdlib.h>
as well. Are their more versions of malloc or something? The compiler didn't
say anything.


You shot yourself in the foot, by casting the malloc call. Without the
cast, the compiler MUST emit a diagnostic, if you don't include <stdlib.h>
because malloc is implicitly declared as returning int, but used in a
pointer context.

The first rule of computer programming: know what you're doing.
The second rule of computer programming: know how to use your tools.

Actually, these rules apply to any human activity...

Compile these two programs and note the difference:

int main()
{
char *p = malloc(10);
return 0;
}

and

int main()
{
char *p = (char *)malloc(10);
return 0;
}

They're both equally broken (due to the lack of declaration for malloc),
but only the first one requires a diagnostic from the compiler.

The next exercise is to find out how to use your compiler so that even
the second program generates a diagnostic, because you're using a function
without declaring it. C89 allows this, but it is such an atrocious idea
that practically all compilers can warn about it, if you raise their
warning level high enough. You really don't want to use undeclared
functions in your programs and, if you have to declare them yourself,
make sure you use prototype declarations.

If the compiler can find your bugs, it is downright idiotic not to let it
do it for you.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #17

P: n/a
Rick wrote:

Do you have magic powers? How do you know I forgot all that stuff? I only
gave a piece of the code, not the complete thing. Anyway, everybody thanks
for helping!

Please quote a relevant portion of the post you are replying to.


Brian Rodenborn
Nov 13 '05 #18

P: n/a
On Wed, 29 Oct 2003 14:31:41 +0100, in comp.lang.c , "Rick"
<as******@hotmail.com> wrote:
Wait! I talk too fast. It does work now, after including #include <stdlib.h>
as well. Are their more versions of malloc or something? The compiler didn't
say anything.


Rick, sorry about this, but I'm going to store your post for
perpetuity, as it a classic example of someone actually getting bitten
by the reason for NOT casting malloc.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #19

P: n/a
On Wed, 29 Oct 2003 14:31:41 +0100, in comp.lang.c , "Rick"
<as******@hotmail.com> wrote:
Wait! I talk too fast. It does work now, after including #include <stdlib.h>
as well. Are their more versions of malloc or something?
There's only one version ,declared in stdlib.h.
The compiler didn't say anything.


Its not required to. Your cast silenced the only warning it could have
made, "implicit conversion from int to pointer". In the absence of a
proper prototype for a function, the compiler assumes that it returns
an int. DONT cast malloc in C code, for this very reason.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #20

P: n/a
Rick wrote:

Wait! I talk too fast. It does work now,
after including #include <stdlib.h> as well.


#include <stdlib.h>, is part of the program code.

When you post code to this newsgroup,
try to post the smallest complete entire program
which exhibits your problem.

--
pete
Nov 13 '05 #21

This discussion thread is closed

Replies have been disabled for this discussion.