473,738 Members | 9,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question regarding malloc casing

Hi All,

I have one question regarding return value cast of malloc.

I learned that we should not cast the return value of malloc because
it is bug hider.
But my question is as mentioned bellow .

Lets say I have not included stdlib.h in my program still I am using
malloc so compiler will throw warring because with out prototype
compiler assumes that function is declared as extern int
malloc() .Suppose I ignore that warning and did not cast the return
value
Now during linking time my code will be linked to exact
implementation of malloc which returns void * . So in this case will
it be a problem?

Regards,
Somenath
Dec 2 '07 #1
10 1903
somenath <somenath...@gm ail.comwrote:
Hi All,

I have one question regarding return value cast of malloc.

I learned that we should not cast the return value of malloc
because it is bug hider.
But my question is as mentioned bellow .

Lets say I have not included stdlib.h in my program still I
am using malloc so compiler will throw warring because with
out prototype compiler assumes that function is declared
as extern int malloc().
If you ignore the bug, the bug remains. Even without an
explanation, I can't this as ever being a Good Thing (TM).
Suppose I ignore that warning and did not cast the return
value
Now during linking time my code will be linked to exact
implementation of malloc which returns void * . So in this
case will it be a problem?
Yes.

On a typical motorola 68k implementaion, the library will
return the pointer in A0, whereas your code will expect
it in D0.

On a stack based implementation where void * is 64 bits
and int is 32-bits, you may find the library function will
clean up too much stack.

Fact is, failing to declare a prototype is seen as such
a weakness in the C language that many people prefer to
tell their compilers to make it an error to call an
unprototyped named function, even though it breaks the
conformance of the compiler. Some even go so far as use
C++ instead of C.

--
Peter
Dec 2 '07 #2
On Dec 2, 10:02 am, Peter Nilsson <ai...@acay.com .auwrote:
somenath <somenath...@gm ail.comwrote:
Hi All,
I have one question regarding return value cast of malloc.
I learned that we should not cast the return value of malloc
because it is bug hider.
But my question is as mentioned bellow .
Lets say I have not included stdlib.h in my program still I
am using malloc so compiler will throw warring because with
out prototype compiler assumes that function is declared
as extern int malloc().

If you ignore the bug, the bug remains. Even without an
explanation, I can't this as ever being a Good Thing (TM).
Suppose I ignore that warning and did not cast the return
value
Now during linking time my code will be linked to exact
implementation of malloc which returns void * . So in this
case will it be a problem?

Yes.

On a typical motorola 68k implementaion, the library will
return the pointer in A0, whereas your code will expect
it in D0.
Many thanks for the response. I just fell to understand this point.
With out prototype compiler assumes that malloc returns int. But
during linking time it will be linked to correct definition of malloc,
which returns (void *). Then in run time it will be returning (void
*) .Is my understanding wrong ?

On a stack based implementation where void * is 64 bits
and int is 32-bits, you may find the library function will
clean up too much stack.
I did not get this point either . How it is a problem ? Could you
please illustrate this point bit more .
Fact is, failing to declare a prototype is seen as such
a weakness in the C language that many people prefer to
tell their compilers to make it an error to call an
unprototyped named function, even though it breaks the
conformance of the compiler. Some even go so far as use
C++ instead of C.
Ok . This is the only point I understood.
Dec 2 '07 #3
somenath <somenath...@gm ail.comwrote:
Peter Nilsson <ai...@acay.com .auwrote:
somenath <somenath...@gm ail.comwrote:
I learned that we should not cast the return value of
malloc because it is bug hider. ...
Lets say I have not included stdlib.h in my program
still I am using malloc so compiler will throw warring
because with out prototype compiler assumes that
function is declared as extern int malloc().
If you ignore the bug, the bug remains. Even without an
explanation, I can't this as ever being a Good Thing (TM).
Suppose I ignore that warning and did not cast the
return value
Now during linking time my code will be linked to exact
implementation of malloc which returns void * . So in
this case will it be a problem?
Yes.

On a typical motorola 68k implementaion, the library will
return the pointer in A0, whereas your code will expect
it in D0.

Many thanks for the response. I just fell to understand
this point.
Do a google for "chinese whispers".

C is typically implemented as a series of processes
(roughly following the translation phases set out in
the standard.) Each of these processes typically
carries an element of trust.

The compiler trusts you the programmer.
The linker trusts the compiler.
The host system trusts the linker.

The weak point is at the beginning. If you lie to the
compiler, everyone trusts each other until the program
actually runs and problems surface.
With out prototype compiler assumes that malloc returns
int.
Yes, and it produces some assembler that _assumes_ the
type of value returned when it calls malloc is an int.

On some systems, that means assuming it comes via a data
register, rather than an address register. On other systems
it assumes that 32 bits need to be allocated on a stack,
instead of 64. On still other systems, it assumes it will
arrive in the living room rather than the garage.

Different systems have different calling conventions. Some
systems use machine registers, some use a hardware stack,
others have combinations of the two, and still others use
even wierder mechanisms.

The fundamental point though is that these calling
conventions fall down (usually quite quickly) if the
compiler uses the wrong one. The only clue to the
correct one comes from you the programmer.
But during linking time it will be linked to correct
definition of malloc, which returns (void *). Then in
run time it will be returning (void *) .
But _where_ this void * is returned is crucial. Since the
compiler has been told to expect it via a completely
different type, there is no guarantee that the assembly
code it produces will correctly match up with how the
function actually returns the value.
Is my understanding wrong ?
You are missing the point that C is a statically
typed language. The return type of a function is not
determined at runtime, it is fixed at compile time. In
this regard, C differs from many modern languages that
prefer to figure things out as they run.

Calling a function is like a messaging system. You
pass arguments to the function and it returns one
back to you (if it's a non-void function like malloc).
How those messages are communicated are agreed to in
advance. You stray from the agreed communication lines
at your peril.

Imagine you send off your courier to deliver a message
to Malloc Pty Ltd asking for a delivery of Memory. You
tell your assistant to pick up the returned package at
Gate 15 of bus terminal. But Malloc Pty Ltd always
delivers at Gate 12. So you miss the package.
On a stack based implementation where void * is 64
bits and int is 32-bits, you may find the library
function will clean up too much stack.

I did not get this point either. How it is a problem?
Could you please illustrate this point bit more .
Suppose you send a family wagon over to Malloc Pty
Ltd to pick up a package. They then put 2 tonnes of
packages into the back and your tyres blow out before
you even leave the pick up dock. Where you agreed to
send a small utility truck, you sent a wagon, and
now you've paid the cost.

--
Peter
Dec 2 '07 #4
somenath <so*********@gm ail.comwrites:
On Dec 2, 10:02 am, Peter Nilsson <ai...@acay.com .auwrote:
>somenath <somenath...@gm ail.comwrote:
[...]
Suppose I ignore that warning and did not cast the return
value
Now during linking time my code will be linked to exact
implementation of malloc which returns void * . So in this
case will it be a problem?

Yes.

On a typical motorola 68k implementaion, the library will
return the pointer in A0, whereas your code will expect
it in D0.
Many thanks for the response. I just fell to understand this point.
With out prototype compiler assumes that malloc returns int. But
during linking time it will be linked to correct definition of malloc,
which returns (void *). Then in run time it will be returning (void
*) .Is my understanding wrong ?
[...]

Yes, and the inconsistency is why it's a problem.

When the compiler sees your call to malloc, it generates code for a
call assuming that malloc returns int. At link time, the call is
resolved to refer to the correct malloc function, which returns void*.
So the malloc function returns a void* result to a caller that's
expecting an int. Hilarity ensues.

Note that on *some* implementations , this will happen to work
(because, say, int and void* happen to be the same size, and happen to
be returned in the same manner). On others, Bad Things Will Happen.

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 2 '07 #5
somenath wrote:
Many thanks for the response. I just fell to understand this point.
With out prototype compiler assumes that malloc returns int. But
during linking time it will be linked to correct definition of malloc,
which returns (void *). Then in run time it will be returning (void
*) .Is my understanding wrong ?
Yes.

You're correct that it links with the right definition. However the
compiler has told the linker that malloc returns an int.

In a stack-based implementation, the calling function will remove an int
from the stack (because thats what it expects). If an int is not
identical in size to a void*, it will remove too much, or not enough,
and corrupt memory.

In other implementations , such as the M86K mentioned, it will try to
read the int from entirely the wrong register, and return garbage data.
>On a stack based implementation where void * is 64 bits
and int is 32-bits, you may find the library function will
clean up too much stack.

I did not get this point either . How it is a problem ? Could you
please illustrate this point bit more .
Lets say you ask the the librarian for Knuth, and he puts two volumes on
top of the pile on his desk. If you were expecting four volumes, then
you will take someone else's books. When you try to use those two extra
books you'll get in a mess. Meanwhile the guy who actually did want
those two books will have got Advanced Calculus instead, and will be
equally in a mess.

Dec 2 '07 #6
On Dec 2, 6:30 pm, Mark McIntyre <markmcint...@s pamcop.netwrote :
somenath wrote:
Many thanks for the response. I just fell to understand this point.
With out prototype compiler assumes that malloc returns int. But
during linking time it will be linked to correct definition of malloc,
which returns (void *). Then in run time it will be returning (void
*) .Is my understanding wrong ?

Yes.

You're correct that it links with the right definition. However the
compiler has told the linker that malloc returns an int.

In a stack-based implementation, the calling function will remove an int
from the stack (because thats what it expects). If an int is not
identical in size to a void*, it will remove too much, or not enough,
and corrupt memory.
Many thanks for the explanation. Please let me verify my understanding
with the explanation what you have provided.

In a stack base implementation when ever one function is called the
arguments are pushed into the stack .Now when the called function
returned a value it put the return value at the top of the stack .So
the calling function can pop the value. Now as the malloc is returning
void * but calling function is expecting int and if the size of void
* != size of int it may pop less or more data which can cause
problem . I would like to know if my understanding is correct?
Dec 2 '07 #7
somenath wrote:
On Dec 2, 6:30 pm, Mark McIntyre <markmcint...@s pamcop.netwrote :
>somenath wrote:
Many thanks for the response. I just fell to understand this point.
With out prototype compiler assumes that malloc returns int. But
during linking time it will be linked to correct definition of
malloc, which returns (void *). Then in run time it will be
returning (void
*) .Is my understanding wrong ?

Yes.

You're correct that it links with the right definition. However the
compiler has told the linker that malloc returns an int.

In a stack-based implementation, the calling function will remove an
int from the stack (because thats what it expects). If an int is not
identical in size to a void*, it will remove too much, or not enough,
and corrupt memory.
Many thanks for the explanation. Please let me verify my understanding
with the explanation what you have provided.

In a stack base implementation when ever one function is called the
arguments are pushed into the stack .Now when the called function
returned a value it put the return value at the top of the stack .So
the calling function can pop the value. Now as the malloc is returning
void * but calling function is expecting int and if the size of void
* != size of int it may pop less or more data which can cause
problem . I would like to know if my understanding is correct?
Essentially yes, but the error need not require a stack at all. Simply
speaking if there is not prototype for malloc() in scope, the compiler
defaults to a return type of int. Therefore it will generate calls to
malloc() suited for an int return type. The actual implementation of
malloc() that you link with, will of course return a void * value.

Now there is no requirement in the Standard that void * and int have the
same size or representation or occupy the same machine level storage
location. For example it may so happen on an implementation that
pointer return values are returned in register r7 while int return
values are returned in register r0.

Therefore when there is no prototype for malloc() and the compiler
assumes it returns an int, it may generate something similar in terms
of machine code for a typical call to malloc():

C code:
int *p = malloc(SIZE);

Asm:
PUSH SIZE
CALL _malloc
ADD 4, SP ; CLEAN UP STACK
MOVE R0, p

Here malloc() returned it's pointer value in register R7 (that is the
convention for this machine), but the compiler stores the value in R0
to the pointer object 'p' because it defaults to assuming malloc()
returns an int, when there is no prototype for it, and in this machine
the default location of an int return value is register R0.

Hence some garbage value that happens to be in R0 will get stored into
your precious pointer 'p' and the code will likely lead to a memory
violation error when you deference the pointer, or to silent memory
corruption.

This example is simply an illustration of the general rule in C that
unless the Standard says otherwise you may not assume that different
types have any similarity with each other or are treated the same at
the machine level.

Overriding the type system of the language, either by an explicit cast
or by errors like above, is dangerous, unless you know exactly what you
are doing on a particular machine and can live with the loss of
portability.

Dec 2 '07 #8
somenath wrote:
>
In a stack base implementation when ever one function is called the
arguments are pushed into the stack .Now when the called function
returned a value it put the return value at the top of the stack .So
the calling function can pop the value. Now as the malloc is returning
void * but calling function is expecting int and if the size of void
* != size of int it may pop less or more data which can cause
problem . I would like to know if my understanding is correct?
Correct.

Dec 2 '07 #9
santosh wrote:
somenath wrote:
>On Dec 2, 6:30 pm, Mark McIntyre <markmcint...@s pamcop.netwrote :
>>somenath wrote:
Many thanks for the response. I just fell to understand this
point. With out prototype compiler assumes that malloc returns
int. But during linking time it will be linked to correct
definition of malloc, which returns (void *). Then in run time it
will be returning (void
*) .Is my understanding wrong ?

Yes.

You're correct that it links with the right definition. However the
compiler has told the linker that malloc returns an int.

In a stack-based implementation, the calling function will remove an
int from the stack (because thats what it expects). If an int is not
identical in size to a void*, it will remove too much, or not
enough, and corrupt memory.
Many thanks for the explanation. Please let me verify my
understandin g with the explanation what you have provided.

In a stack base implementation when ever one function is called the
arguments are pushed into the stack .Now when the called function
returned a value it put the return value at the top of the stack .So
the calling function can pop the value. Now as the malloc is
returning
void * but calling function is expecting int and if the size of void
* != size of int it may pop less or more data which can cause
problem . I would like to know if my understanding is correct?

Essentially yes, but the error need not require a stack at all. Simply
speaking if there is not prototype for malloc() in scope, the compiler
defaults to a return type of int. Therefore it will generate calls to
malloc() suited for an int return type. The actual implementation of
malloc() that you link with, will of course return a void * value.

Now there is no requirement in the Standard that void * and int have
the same size or representation or occupy the same machine level
storage location. For example it may so happen on an implementation
that pointer return values are returned in register r7 while int
return values are returned in register r0.

Therefore when there is no prototype for malloc() and the compiler
assumes it returns an int, it may generate something similar in terms
of machine code for a typical call to malloc():

C code:
int *p = malloc(SIZE);
Correction: Forgot the all important cast of malloc() return value and
why it may lead to errors.

int *p = (int *)malloc(SIZE);

<snip rest>

Dec 2 '07 #10

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

Similar topics

5
2483
by: lixiaoyao | last post by:
hi all I use matrix & vector function to allocate the space myself in c, typedef struct matrix_array newdata; struct matrix_array{ float **sy,*sxx; }; newdata ndata;//new data struct ndata.sy=matrix(1,nvar,1,nstep); ndata.sxx=vector(1,nstep);
19
770
by: amanayin | last post by:
Why does this program run in the ddd debugger but when i try to run the program in a konsole i get a segmentation fault. I just can't work it out the OS i use is suse 8.2 pro program below: /* OVERLAY.C OVERLAY OF STRINGS */ #include<malloc.h> #include<string.h> #include<stdio.h> #define MAX_LEN 40 int main(void)
36
2275
by: Martin Andert | last post by:
Hello, I have a question regarding malloc and free. Here my code sample: int main() { /* allocating dynamic memory for array */ int* array = (int*) malloc(5 * sizeof(int)); /* ... program code ... */
39
3497
by: Patrick | last post by:
The c# code style guide that I follow suggests that class variables (fields) be coded with camel casing, like this: int recordId; string name; It also suggests that variables within methods and method parameters use camel casing, like this: void SetName(int id, string newName)
19
1509
by: lawtrevor | last post by:
I have a question regarding the use of free() based on some code I need to decipher: { struct A {<A fields>}; struct B {<A fields+ <Bfields>}; typedef struct A Aobj; typedef struct B Bobj;
2
3799
by: somenath | last post by:
Hi All, I have one question regarding the alignment of pointer returned by malloc. In K&R2 page number 186 one union is used to enforce the alignment as mentioned bellow. typedef long Align; union header { struct {
6
1420
by: mattmao | last post by:
emmm, this is taken from the exam I just finished this morning: Which one is correct: A) double *ptr = (double *) malloc(100 * sizeof(double)); B) double *ptr = (double *) malloc(100 * sizeof(double *)); C) double ptr = (double) malloc(100 * size0f(double)); D) double *ptr = (double) malloc(100*sizeof(double)); My choice is A.
7
2168
by: somenath | last post by:
Hi All , As a process of my C language learning I was trying to learn how malloc can be implemented from K&R2 .But I am not able to understand few points . It would be very much helpful if some body give some inputs in the bellow mentioned points. Point 1) I page 186 it is said that "In malloc, the requested size in characters is rounded up to the proper number of header-sized units; the block that will be allocated contains one...
2
2399
by: Madmartigan | last post by:
Hi Operating system is WinXP using SharpDevelop version 1.1.0 and build 2124. I'm new to C# and have a problem trying to get a user to enter 3 mathematical operators of choice, then 2 numbers of choice, and giving ouput for each of the mathematical operations using the 2 numbers. The general script will work but I have a user inputting a string which I don't know how to convert to int to be capable of using it in mathematical...
0
8969
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9335
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...
0
9208
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
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6053
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
4570
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
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2745
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.