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

C + Malloc

Hi...i'm writing from Rome...and i don't know english very well so...
Only simple question, which is the difference between those two parts of
code.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;
I really need to allocate memory before assign an address to a pointer
variable?.
Thus because i know that declaration not allocate memory for pointer
variable.
Is correct ?.

Thanks all..

Nov 14 '05 #1
8 1774
Le jeudi 14 octobre 2004 à 11:45, lasek a écrit dans comp.lang.c*:
Hi...i'm writing from Rome...and i don't know english very well so...
Only simple question, which is the difference between those two parts of
code.
The second piece of code has a bug called a memory leak.
[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;

I really need to allocate memory before assign an address to a pointer
variable?.
Yes but calling malloc() is only one way of allocating memory. Defining
a variable is another way.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

You allocated a small piece of memory when you defined iVar. Then you
put the address of that memory into pInt. This code is correct. Note
that iVar will go away when you leave the current block of code.

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;

You allocated a small piece of memory when you defined iVar. Then you
dynamically allocated another small piece of memory by calling malloc()
and put its address into pInt. Finally you put the address of iVar into
pInt *and lost the only copy of the address of the dynamically allocated
memory; you need to free it by calling free(), but now you can't because
you don't have its address anymore...
Thus because i know that declaration not allocate memory for pointer
variable.


Each time you define a variable, you allocate memory for the variable.
If it's a pointer, you allocate memory for the pointer itself but not
the memory you want to point to.
--
___________ 14/10/2004 12:02:35
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
Nov 14 '05 #2
lasek <cl**************@acrm.it> wrote:
Only simple question, which is the difference between those two parts of
code. [FIRST]
int *pInt=NULL;
int iVar=10; This is a definition, so iVar object is allocated automatically. pInt=&iVar; Correct, pInt points to iVar object.
[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int)); Correct, you allocate new memory and assign pInt to it. pInt=&iVar; Correct, but you reassign pInt back to iVar object again.

I really need to allocate memory before assign an address to a pointer
variable?.
No, when you define a variable, the memory is allocated automatically.
The variable is the object, and a pointer may point to it.

Simplifying a little, one can say that you can have as many objects
as many variables you have in your program. If you need more objects,
then you need to allocate.
Thus because i know that declaration not allocate memory for pointer
variable.
Is correct ?.


Correct. Pointer definition automatically allocates memory only for
the pointer variable itself (yes, the pointer is also kind of object),
but *not* for what the pointer is supposed to point at (the pointer is
said to be "dangling", until you assign to something valid).

--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05 #3
lasek wrote:
Hi...i'm writing from Rome...and i don't know english very well so...
Only simple question, which is the difference between those two parts of
code.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;
I really need to allocate memory before assign an address to a pointer
variable?. No. with malloc above, you get some memory allocated and the pInt
points to that memory.
then you make pInt point to iVar, which already have storage, and the
pointer to the storage allocated with malloc is lost(creating a memory
leak)
Thus because i know that declaration not allocate memory for pointer
variable.
Is correct ?.

It is, but there is no need for allocating storage for it if you make it
point to something which already have storage.
Nov 14 '05 #4
"lasek" <cl**************@acrm.it> wrote:
Hi...i'm writing from Rome...and i don't know english very well so...
Sono certo che parlai miglior Inglese che io parlo Italiano.
[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;
This is correct.
[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
No need to cast malloc(). This is more solid:

pInt=malloc(n * sizeof *pInt);

(Oh, and you do remember to #include <stdlib.h> when using malloc(),
right?)
pInt=&iVar;
Ah, and this is wrong.
I really need to allocate memory before assign an address to a pointer
variable?.
No. Quite the contrary, in fact. You need to _either_ allocate memory
using malloc() or similar functions, _or_ assign the pointer to the
address of an existing object.
By doing both, you have in fact created a memory leak. You've allocated
memory using malloc(). You have _one_ pointer containing this memory's
address: pInt. And in the next line, you scribble over that address, and
pInt now contains the address of iVar, rather than the address of the
allocated block. Now the problem is: how are you going to free that
block of memory? You've lost its address; what are you going to pass to
free()?
Thus because i know that declaration not allocate memory for pointer
variable.


Well...

int *ptr;

does allocate memory for ptr _itself_, just as

int i;

allocates memory for one int, called i. What it doesn't do is allocate
memory for ptr to point at. But that doesn't mean that you have to
explicitly do so yourself.
You _must_ point ptr at a valid bit of memory before using *ptr; but it
doesn't matter whether you point it at memory you got from malloc(), or
at memory occupied by an existing int, say, at i. Except, of course,
that memory you got from malloc() needs to be free()d, and normal
variables shouldn't.

Richard
Nov 14 '05 #5
On Thu, 14 Oct 2004 05:45:02 -0400
"lasek" <cl**************@acrm.it> wrote:
Hi...i'm writing from Rome...and i don't know english very well so...
Not a problem. Your English is better than my Roman... ;-)
Only simple question, which is the difference between those two parts
of code.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;
This is correct.
[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;
This is a memory leak and so bad.
I really need to allocate memory before assign an address to a pointer
variable?.
No.
Thus because i know that declaration not allocate memory for pointer
variable.
Sorry, not with you here.
Is correct ?.

Thanks all..


Your first example is correct, the second is definitely not what you
wanted. You only call malloc what you want some new memory, not when you
want to access memory you already have.

Also, a note on calling malloc when you *do* want it. Calling it like
this would be better:
pInt=malloc(no_of_elements * sizeof *pInt);
As you can see, if you change the type of pInt the above means you don't
need to change the call to malloc.

Also, calling malloc without a prototype in scope (because you forgot to
#include <stdlib.h>) invokes undefined behaviour and on some systems
*will* cause problems. If you don't cast the return value of malloc the
compiler *will* generate a diagnostic (either a warning or an error)
telling you that you got something wrong. The warning may not say
exactly what is wrong, but at least it will tell you that *something* is
wrong.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #6
In <ca******************************@localhost.talkab outprogramming.com> "lasek" <cl**************@acrm.it> writes:
Hi...i'm writing from Rome...and i don't know english very well so...
Only simple question, which is the difference between those two parts of
code.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;
In the second part you're creating a memory leak, because you're losing
the address of the memory block allocated by malloc. It will remain
allocated until program termination, but you can no longer access it,
because you have lost its address.
I really need to allocate memory before assign an address to a pointer
variable?.
How else can you obtain the address to be assigned to the pointer?
Thus because i know that declaration not allocate memory for pointer
variable.
Is correct ?.


Nope. Declaration doesn't allocate memory for anything, but definition
does allocate memory for the pointer variable, which has its own address
like any other variable. Before *assigning a value* to the pointer
variable you need to obtain that value somehow. There are three portable
methods:

1. Use the value of another pointer variable.

2. Use the unary & operator.

3. Use malloc and friends.

A 4th, non-portable method, consists in converting an integer value to a
pointer value, via a cast operator.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #7
lasek wrote:

Hi...i'm writing from Rome...and i don't know english very well so...
Only simple question, which is the difference between those two parts of
code.

[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;

[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;

I really need to allocate memory before assign an address to a pointer
variable?.
Thus because i know that declaration not allocate memory for pointer
variable.
Is correct ?.


No it isn't. The first is correct. The second creates a useless
memory leak. You should also eliminate the useless casts and the
ugly hungarian notation. Blanks around operators are a great aid
to legibility.
--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #8
Thanks all for the answers...in effect, i've forgotten in my mind that
malloc return an address, so the line (ptInt=malloc....) have no meaning
if i readdress the variable pointer with another address (&stuff).

For stdlib i know the headers files but simply not reported in the
textarea.

best regards..


Nov 14 '05 #9

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

Similar topics

19
by: john smith | last post by:
Can someone please explain to me what is happening when I do a malloc(0). This is what I did. int* p = (int*)malloc(0); Then I printed the value of p and of course it was non-null. But...
34
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
20
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
40
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd...
71
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a...
23
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef...
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: 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: 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: 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
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...

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.