Newbie question about "malloc" ???

G

George

Hello to everybody,

The following code works properly,
but what's the hint with the Dynamic Memory Allocation ???
If i don't specify the ammount of memory that i wish to
allocate (f.e.10), this programm won't work.
So how can we say that "malloc" is used
for dynamic memory allocation ???

I appreciate any help/explanation
Many thanks in advance......


#include <iostream>
using namespace std;

int main()
{
char* name;
name=(char*)malloc(sizeof(char)*10);
if (!name)
{
cout << "Memory Allocation Error.";
exit (0);
}
cout << "Enter your name:";
cin >> name;
cout << "Your name is :" << name;
getchar();
return 0;
}
 
L

Lew Pitcher

George said:
Hello to everybody,

The following code works properly,
but what's the hint with the Dynamic Memory Allocation ???
If i don't specify the ammount of memory that i wish to
allocate (f.e.10), this programm won't work.
So how can we say that "malloc" is used
for dynamic memory allocation ???

I appreciate any help/explanation
Many thanks in advance......


#include <iostream>
Nonstandard header.
using namespace std;
Syntax error

int main()
{
char* name;
name=(char*)malloc(sizeof(char)*10);
1) missing header
2) unnecessary cast to (char *)
3) unnecessary sizeof(char)
if (!name)
{
cout << "Memory Allocation Error.";
Syntax error: can't leftshift by a pointer value
exit (0);
}
cout << "Enter your name:";
Syntax error: can't leftshift by a pointer value
cin >> name;
Syntax error: can't rightshift by a pointer value
cout << "Your name is :" << name;
Syntax error x 2: can't leftshift by a pointer value
getchar();
Missing header or missing code
return 0;
}

Are you /sure/ that this is C code? It looks a lot like c++ code to me, and
if it is, then it's certainly off-topic for comp.lang.C
 
D

Dan Pop

In said:
The following code works properly,
but what's the hint with the Dynamic Memory Allocation ???
If i don't specify the ammount of memory that i wish to
allocate (f.e.10), this programm won't work.
So how can we say that "malloc" is used
for dynamic memory allocation ???

It is dynamic, because the amount of memory need not be known at
compile time, as it is in your example. Have a look at the following
(properly written) C program instead.

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

int main(int argc, char **argv)
{
int bytes;
char *p;

if (argc < 2) bytes = 1000;
else bytes = atoi(argv[1]);

if (bytes < 0) {
puts("Get lost, idiot!");
return 0;
}

p = malloc(bytes);
if (p != NULL) printf("Successfully allocated %d bytes.\n", bytes);
else printf("Failed to allocate %d bytes.\n", bytes);

return 0;
}

Can you see now the dynamic nature of the allocation?

Dan
 
R

Robert Stankowic

George said:
Hello to everybody,

The following code works properly,
but what's the hint with the Dynamic Memory Allocation ???
If i don't specify the ammount of memory that i wish to
allocate (f.e.10), this programm won't work.
So how can we say that "malloc" is used
for dynamic memory allocation ???

I appreciate any help/explanation
Many thanks in advance......

C++ stuff snipped.

I think you mix up "dynamic allocation" and "dynamic arrays".
malloc() is used to request some memory at runtime (dynamically). To resize
the memory malloc() gave you (to have a "dynamic array") you can use
realloc() which, if successful, shrinks/grows the memory you got, thereby
preserving the contents of the original block up to the size of the
reallocated block.
HTH
Robert
 
D

Dan Pop

In said:
Are you /sure/ that this is C code? It looks a lot like c++ code to me, and
if it is, then it's certainly off-topic for comp.lang.C

The code is off-topic, but the actual question isn't: it's a legitimate
question about malloc, which is a standard C feature. Yet, you have
chosen not to address it, simply because the code that was supposed to
illustrate it was broken...

Dan
 
D

Default User

Dan Pop wrote:
The code is off-topic, but the actual question isn't: it's a legitimate
question about malloc, which is a standard C feature. Yet, you have
chosen not to address it, simply because the code that was supposed to
illustrate it was broken...


However, a redirect is probably appropriate. If the OP is actually
programming in C++, as it appears, then he shouldn't be using malloc()
at all.

C groups for C, C++ groups for C++.



Brian Rodenborn
 
G

glen herrmannsfeldt

Dan Pop wrote:

(snip)
It is dynamic, because the amount of memory need not be known at
compile time, as it is in your example.

(snip)

Well, it can be dynamic even if it is known at compile time,
though it is more useful when it doesn't need to be.

Static memory on most systems must have a known size at
compile time.

-- glen
 
G

George

Hi people.....
I'm George and i realy want to thank you
a lot for the answers!
Sorry tha i posted this question here....but i thought
that "malloc" is more a C matter then C++.
Thanks again!
 
J

Joona I Palaste

George said:
Hi people.....
I'm George and i realy want to thank you
a lot for the answers!
Sorry tha i posted this question here....but i thought
that "malloc" is more a C matter then C++.
Thanks again!

Of course "malloc" is more a C matter than C++. You shouldn't be
apologising about asking about C matters on comp.lang.c. In fact, IIRC
the only non-C matters in your example code were those << and >>
thingies.

--
/-- Joona Palaste ([email protected]) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You have moved your mouse, for these changes to take effect you must shut down
and restart your computer. Do you want to restart your computer now?"
- Karri Kalpio
 
C

Chris Torek

Of course "malloc" is more a C matter than C++. You shouldn't be
apologising about asking about C matters on comp.lang.c.

Indeed not -- but I would rephrase the first statement. The
malloc() function exists in both C and C++ -- but its correct
and proper usage is quite different in the two languages. In
C, "best practice" in general is:

var = malloc(N * sizeof *var);

C++ almost always requires a cast, and in C++, "best practice" in
general is not to use malloc() at all. (Usually you should use
either "new" or a container-class, though you might use malloc()
and realloc() to implement container-classes, if for some reason
the forty bazillion existing ones are all unsuitable :) .)
 
D

Dan Pop

In said:
However, a redirect is probably appropriate. If the OP is actually
programming in C++, as it appears, then he shouldn't be using malloc()
at all.

C groups for C, C++ groups for C++.

Yet, the question was about malloc, which happens to be a C feature.
Redirecting questions about malloc is downright stupid, unless they
involve implementation-specific aspects (which was not the case here).

Dan
 
D

Dan Pop

In said:
Dan Pop wrote:

(snip)


(snip)

Well, it can be dynamic even if it is known at compile time,
though it is more useful when it doesn't need to be.

It can be, but this is not where it derives its name. Hence the OP's
confusion, which I tried to clarify, rather than consolidate.
Static memory on most systems must have a known size at
compile time.

And then we have automatically allocated memory, which is actually another
form of dynamically allocated memory, especially in C99.

Dan
 
G

glen herrmannsfeldt

Dan Pop wrote:

(snip)
It can be, but this is not where it derives its name. Hence the OP's
confusion, which I tried to clarify, rather than consolidate.
And then we have automatically allocated memory, which is actually another
form of dynamically allocated memory, especially in C99.

PL/I calls the storage attributes STATIC, AUTOMATIC, and CONTROLLED.
Those are the language keywords for them. C only seems to have
static as a keyword. Automatic seems to be a commonly used word
for that type of dynamic allocation, but I don't think anyone
ever uses controlled for the memory allocated by malloc().

Yes, automatic allocation is dynamic, and in C89 must have a
constant size.

-- glen
 
A

August Derleth

Joona I Palaste said:
Of course "malloc" is more a C matter than C++. You shouldn't be
apologising about asking about C matters on comp.lang.c.

Well, it's important to stress the differences between C and C++,
especially when such differences directly impact the possible answers
to the question.

In C, for example, malloc() is never casted, as it returns a pointer
of type void*, which will be implicitly coerced to the correct type.
malloc() is also commonly used whenever dynamic allocation is needed.

In C++, malloc() is usually casted, as no such auto-coercion takes
place. malloc() is also somewhat deprecated in favor of `new',
something that does not exist in C at all.

But the concept of dynamic memory allocation is the same in both
languages: It allows the programmer to allocate memory on the fly,
while the progam is running, and in amounts calculated by the program
itself. It is balanced by the responsibilty to use the allocation
functions correctly and to always de-allocate what you have allocated.
Such ideas are largely language-independent, assuming each language
under discussion supports the concept of dynamic memory allocation.
In fact, IIRC
the only non-C matters in your example code were those << and >>
thingies.

Well, not really. Lew Pitcher gave a full accounting of the C++ code's
failure to be C code in his first response to this thread. It amounts
to the << and >> operators (which are part of the I/O stream syntax),
the `using namespace std;' bit, and including the directive `#include
<iostream>' while excluding the directives `#include <stdio.h>' and
`#include <stdlib.h>'.

His code could be trivially ported to C, as Dan Pop showed, but as it
stood it was fundamentally flawed from the C Standard's viewpoint.

(Not that this makes much difference, mind you. I merely take delight
in recounting random details on Usenet. It's nothing personal.)
 
D

Dan Pop

In said:
Dan Pop wrote:

(snip)




PL/I calls the storage attributes STATIC, AUTOMATIC, and CONTROLLED.
Those are the language keywords for them. C only seems to have
static as a keyword.

Have they dropped "auto" from the keyword list behind my back? ;-)
It's by far the most useless keyword, but it's still there.

Dan
 
K

Kevin Goodsell

Dan said:
Have they dropped "auto" from the keyword list behind my back? ;-)
It's by far the most useless keyword, but it's still there.

Dan

Historically I'd say "entry" was more useless, though it was also
short-lived.

Is there any case where "auto" can be used to change the meaning of a
program (without making the program invalid)?

-Kevin
 
R

Richard Heathfield

Kevin said:
Historically I'd say "entry" was more useless, though it was also
short-lived.

Is there any case where "auto" can be used to change the meaning of a
program (without making the program invalid)?

C89:

#include <stdio.h>

int i;

void foo(void)
{
auto i = 6;
}

int main(void)
{
foo();
printf("%d\n", i);
return 0;
}

Remove auto to get different output.
 
R

Randy Howard

#include <stdio.h>

int i;

void foo(void)
{
auto i = 6;
}

int main(void)
{
foo();
printf("%d\n", i);
return 0;
}

Remove auto to get different output.


Excellent. :)
 
K

Kevin Goodsell

Richard said:
C89:

#include <stdio.h>

int i;

void foo(void)
{
auto i = 6;
}

int main(void)
{
foo();
printf("%d\n", i);
return 0;
}

Remove auto to get different output.

OK, that answers the question I actually asked, but not the question I
meant to ask. ;)

I guess the real question was, "Is there any case where 'auto' can be
used, where it's not trivial to accomplish the same task without the use
of 'auto'?"

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top