Malloc() function in C -- returns void or character pointer?

I've been learning about the free store and heap memory and what not, and I've got two books telling me two different things. One is telling me that the malloc() function returns a void pointer (note: this book has been wrong before) and the other is telling me that it always returns a character pointer. Which is correct? Thanks!

Tron55555 wrote:
when you say "if it's declared as returning a char pointer", are you referring to a theoretical scenario with a different compiler that has declared malloc as returning a char pointer instead of a void pointer? Do I have your meaning right?
Yes. I think void* is standard, but I recall seeing it declared otherwise. The runtime library is written by programmers and a little time spent in this forum should convince you that programmers don't always agree on what's correct.
This seems to be the case with Xcode, right?
Yes. That's why I referred you to the manual page from the Darwin layer. The manual installed there should reflect the current version of gcc, which is the C compiler under Xcode. From the occasional unfortunate experience, we also know that "should" doesn't always equate to "is". But just use that manual and you'll do fine.
Until I read about this in my other book, I never used casts with the malloc function and it always worked fine. Do you think it would be good programming practice for me to get used to writing the function with a cast in case I ever come across a compiler that requires it? I mean it couldn't hurt to write it that way right, even if I am using a compiler that declares malloc as returning a void pointer and doesn't require a cast?
This is more a question of programming style. Type casts turn off the compiler's type checking. So in most cases, type casts are to be avoided. In the case of malloc, everyone knows the game, so an optional type cast depends on what you consider good style. The goal of all the style rules, from indenting to commenting, is to make it easy for someone else to read your code and understand it well enough to make a required change. So we ask ourselves, "What would I like to see 10 years from now when I won't even believe I wrote this stupid code?".
\- Ray
p.s.: Et's excellent point about byte alignment is a wonderful example of how a type cast can get you on the fast track to trouble. Casting a pointer returned from malloc is fine. But casting a pointer after it's been used could cause a problem. Byte alignment in this case means that an int can't start on an odd numbered memory location (I think it might need to be an address divisible by 4 on a 32-bit machine, but that's an Et question--especially as he's responsible for adding the subject of byte alignment to your thread). - R

Similar Messages

  • Request: Make Keyword 'function' Optional for Parameterless/Void Functions

    Say I have function
    doJob (startThis:function(), whenDone:function()) When I am using this function doJob(), it would be nice to be able to do
    doJob( {code_to_do_something}, {code_to_do_something});
    // instead of
    doJob( function(){code_to_do_something}, function(){code_to_do_something});Or be able to define a parameterless void function as
    var hello = {println ("Hello")}; and invoke that function using form
    hello();This would eliminate some verbosity introduced by the function keyword.

    @PhiLho
    Yes, to you just 10 character is not a big deal. But to the rest of us who have to keep repeating those 10 chars over and over in larger applications it does become a big deal.
    Your example of ar foo = {fooCall("Stuff"}; is misplaced. Why would you trap a non-void function call inside a void fn? If fooCall returns something then obviously the compiler would try to return via the calling function and this is a problem (as you point out) regardless of what the syntax is.
    My suggestion is more toward bringing sensible syntax shortcut/sugar in the language.

  • I'm having trouble with this line: public function initHandler(event:EVENT):void

    I'm building a simple photo gallery in Flash CS4 & I've posted the entire code below, if anyone can see the problem in this code, please let me know....thanks. This code is actually from a tutorial: http://blip.tv/file/1620128/
    The tutorial had no issues with this code so I'm wondering if its just a matter of correcting a property or setting somewhere.....
    package videocode
        import flash.display.*;
        import flash.events.*;
        import flash.net.*;
        public class videoview extends MovieClip
            public var source:*;
            public var loader:Loader;
            public var loaderIndex:Number = 1;
            public function videoview()
            loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
            addChild(loader);
            loadImage();
            public function initHandler(event:EVENT):void
                source = loader.content
                source.alpha = 0;
                source.x = videoarea_mc.x;
                source.y = videoarea_mc.y;
                addEventListener(Event.ENTER_FRAME, enterFrameHandler);
                protected function changeHandler(event:Event):void
                    loaderIndex = photoStepper.value
                    loadImage();
                protected function enterFrameHandler(event:Event):void
                    if (source.alpha <1){
                        source.alpha+= .1;
                    } else{
                        removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
                public function getPath():String
                    return("images/image"+loader.Index+".jpeg")
                public function loadImage():void
                    loader.load(new URLRequest[getPath()]);

    public function initHandler(event:Event):void
    only the 'E' should be uppercase

  • Please Help regard function that will return values of each JComboBox items

    I'd like to create a function that will return values of each item on the JComboBox at a time when
    I click on each item of a comboBox. I had this following codes, but didn't work.
    Please help me !!!Please correct it... thanks a million
    String wp;
    String text;
    String A[] = {"WARNIGNS","CAUTIONS","NOTES"};
    JComboBox ABC = new JComboBox();
    for (int i=0;i<A.length;i++) {
    ABC.addItem (A);
    text = Get_It(); //assigns each value of JComboBox's item to variable text when clicks at each item
    //of a comboBOx
    private String Get_It(){
    ABC.addActionListener(new ActionListener (){
    public void actionPerformed(ActionEvent e){
    wp = (String)CBweapon.getSelectedItem() ;
    return wp;

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class AlertFrame extends JFrame {
    String s_alert[] ={"WARNIGNS","CAUTIONS","NOTES"};
    JComboBox CBweapon;
    String wpText;
    public AlertFrame() {
    super("Alerts");
    Container contentPane = getContentPane();
    contentPane.setLayout(null);
    setSize(600,600);
    CBweapon = new JComboBox();
    for (int i=0;i<s_weapon.length;i++) {
    CBweapon.addItem (s_weapon);
    contentPane.add(CBweapon);
    CBweapon.setActionCommand("");
    //set position for components
    CBweapon.setBounds(370 + insets.left,295+ insets.top, 150,30);
    System.out.println(getit()); //calling getit() function
    //this function will be return a String of JcomboBOx value if click on each item of combobox
    private String getit(){
    CBweapon.addActionListener( new ActionListener (){
    public void actionPerformed(ActionEvent e){
    wpText = (String)CBweapon.getSelectedItem() ;
    return wpText;
    public static void main(String args[]) {
    AlertFrame af = new AlertFrame();
    af.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    **I have no errors on compile or run, but it didn't return a string value to System.out.println(getit());
    It maybe because of the "void" of public void actionPerformed(ActionEvent e){
    wpText = (String)CBweapon.getSelectedItem() ;
    Please help me

  • What is the Function MOdule that returns the fields in database table order

    Hello Folks
      I have a dynamic internal table with fields ( which are not in order). I want to display them in the order of which they are present in the database table? Is there any function module that returns the fields in database order?
    FAQ. Please search before posting your question.
    Edited by: Suhas Saha on Oct 10, 2011 10:19 PM

    Hi,
    You can use this BAPI.
    <b>BAPI_SALESORDER_GETLIST</b>
    Reward if useful.
    Regards,
    Vimal

  • How to use Call library function node for a function in dll with VOID data type

    Hi All,
    I would like to ask for your kind help,
    I am facing an issue with the call library node.
    I have a C++ function(stdcall), which has void as data type
    error code XXXX(hwnd, lID, getValue, *void data1, *void data2)
    the data1 and data2 types are always changing depending upoin the value of "getValue".
    Primarily i can use call library node multiple times and adapt each node according to the data types of data1 and data2, and extract the values and use in the code. Here is no issue. Real question is:
    My question:
    How can i just use one time call library node and make a case depending upon the "getvalue", which will control the data type of data1 and data2. Here i really looking for solutions.
    My trials:
    i used varaints as input to the call libray node for data1 and data2, and selected Parameters in call libraby node as " Adapt to type". here labview just crashed.
    i really appreciate your feedbackand suggestions.
    Thanks
    Kutbuddin
    Solved!
    Go to Solution.
    Attachments:
    Clipboard02.jpg ‏103 KB

    A variant is a very specific LabVIEW datatype (really a C++ type object internally) and trying to pass that to a function, which excepts a flat memory pointer there, for sure will crash very quickly.
    As to endianess, yes Unflatten will be able to adjust for endianess, which in this case however is most likely exectly NOT what you want. So make sure that the you select native type for the endianess input on Unflatten from String. LabVIEW internally works with whatever is the native endianess, as will most likely your C++ DLL. The platform independent big endian format does only come into play when you receive data streams over some streaming interface like a network connection. Here it is desirable to use an endian format that is independent from the actual platform that generates and consumes the data stream. LabVIEWs default endianes is big endian here.
    But as long as you pass data directly to native components like DLLs there is no difference in endianess between what LabVIEW uses and what those components use.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Copy to Goods Receipt PO function on Goods Return

    In current version 2007A there is no Copy to Goods Receipt PO function on Goods Return document. There is only Copy to A/P Credit Memo. This list should contain all available target documents.

    Yes, you can.  You just need to go to add A/P invoice and click on Copy From button.  Then select multiple GRPO to copy.  However, you will be warned that only target FX rate can be used if you have BP currency instead of LC.
    Thanks,
    Gordon

  • How to create a procedure function with a return value of ref cursor?

    Can anybody provide a sample about how to create a procedure function with a return value of REF CURSOR?
    I heard if I can create a function to return a ref cursor, I can use VB to read its recordset.
    Thanks a lot.

    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • Function Module to return WSDL URL

    Hi,
    Is there an ABAP Function Module that returns the URL of the WSDL when passed the name of a BAPI/ RFC?
    Thanks,
    Tristan

    hi there,
    unfortunately, as far as I know, there is no official API for the functionality you are talking of.
    Inofficially you might want to have a look at cl_srt_*, especially cl_srt_registry or cl_srt_tools. those classes supply the required functionality.
    be warned though that things are changing with the latest servicepacks and the new transaction SOAMANAGER and it's underlying data model. the new functionality does again not supply an official API to query the information you (and I) would like to get from the system.
    hope it helps, anton

  • Can i use malloc function while using DLL created from C program

    Hi,
    I have written a simple program in C , which uses malloc function for allocating memory for the array.When iam calling that DLL using call library function node in labview, it is not giving any output, my doubt is can we use malloc function in C program from which we will create DLL and is called in labview? I am attaching my C code and DLL and also labview file please tell me where i am doing wrong?
    Thanks & Regards,
    Vishnu
    Attachments:
    first.zip ‏1010 KB

    Hi Vishnu,
    There's no problem using the Malloc function in C and call it as a DLL in LabVIEW.
    But LabVIEW has a different memory management than C.
    It is probably not recommended to allocate array memory in C for labVIEW arrays
    You can use initialize array in LabVIEW instead.
    Good luck
    Van L
    NI Applications Engineer

  • (function ($) { // Checks if a given element resides in default extra leaving container page. function isInExtraLeavingContainer(element) { return $(element)

    [email protected] my xbox 360 (function ($) { // Checks if a given element resides in default extra leaving container page. function isInExtraLeavingContainer(element) { return $(element)

    I suspect it has something to do with the java but not sure
    Just so you'll know, there is no Java on that page.  There is, however JavaScript.  You should know that those two things are different as night and day.
    To fix your problem, change this -
    function MM_swapImgRestore() { //v3.0
      var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
      </script>
    </head>
    to this -
    function MM_swapImgRestore() { //v3.0
      var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
    -->
      </script>
    </head>

  • [svn:fx-trunk] 4964: Modify AccImpl.as to add @private to ?\226?\128? \156protected final function $eventHandler(event:Event):void?\226?\128? \157 to work around an ASdoc bug.

    Revision: 4964
    Author: [email protected]
    Date: 2009-02-16 09:41:50 -0800 (Mon, 16 Feb 2009)
    Log Message:
    Modify AccImpl.as to add @private to ?\226?\128?\156protected final function $eventHandler(event:Event):void?\226?\128?\157 to work around an ASdoc bug. i will remove it when the bug gets fixed.
    QE Notes: None
    Doc Notes: None
    Bugs: -
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/accessibility/AccImpl.as

    I forgot to write down my computer specs:
    iMac 27 Mid 2011
    2.7 GHz Intel Core i5
    4 GB 1333 MHz DDR3
    AMD Radeon HD 6770M 512 MB
    OS X 10.9.2

  • SSAS- DAX expression : Is there any DAX function that can return multiple values ?

    Hi,
    Iam in search of a DAX function that can return multiple values as result. please find below scenario where i want to implement the same.
    I have three  Tables: Table A (typeid, Cost, Qty ) ,Table B (typeid, Cost, Qty ) , Table C ( typeid,Typename ) .
    Table A                                       Table B                               
    Table C
    type id  cost  Qty             type id   Cost    Qty                 
    typeid  typename
    1           100    100                3         300     
    300                  1           aa
    2           200    200                4          400    
    400                  2           bb
                                                                                             3           cc
                                                                                             4          
    dd 
    i have to club cost and Qty of two tables(four measures)  as two measures in the  UI report. There are more columns in these tables that restrict the  UNION of the tables.(for the sake
    of understanding , i have not mentioned the othr columns). In the UI report(Execl 2013-power pivot) iam plotting these measures against the
    Table C.Typeid. Hence the measures drill down against each 
    Table C. Typeid as shown below:
    Typeid  Table A.cost  Table A.Qty  TableB.cost  TableB.Qty                              
    1              100             100
    2              200             200
    3                                                    
    300             300      
    4                                                    
    400             400
    My requirement is to club these measures so that the report will be as below
    Type id  cost   Qty
    1          100    100
    2          200    200
    3         300     300
    4         400      400
    Since i cannot club these in model,as a work around, i created a calculated measure in excel(Analyze tab->Calculations->olap tools->calculated measure) with the condition as below:
    new cost = IIF (ISEMPTY(TableA.cost)="TRUE",TableB.cost,TableA.cost)
    new Qty = IIF(ISEMPTY(TableA.Qty)="TRUE",TableB.Qty,TableA.Qty) and dragged these new measures into the report. It was working fine as expected.
    But  this functionality of Creating calculatedmeasure in excel report is possible only in 2013 excel version.
    Now the requirement is to get the same result in 2010 excel. Can you please help me in implementing the same in 2010 excel? or any other alternative method to bring the columns in model itself. I tried to create a measure in table A with DAX expression as
    : new cost :=CALCULATE(SUM(Table B.cost),ISBLANK(TableA.cost)) -> but this will return only 1 result .i need Sum(Table A.cost) also if it is not blank.
    Thanks in advance

    You can use SUMX ( 'Table A', 'Table A'[Cost] + 'Table B'[cost] )
    However, if you install the latest version of Power Pivot in Excel 2010, it supports the ISEMPTY function, too.
    http://support.microsoft.com/kb/2954099/en-us
    Marco Russo http://www.sqlbi.com http://www.powerpivotworkshop.com http://sqlblog.com/blogs/marco_russo

  • Jpa native query returns only first character of a field

    Hi,
    I've a JPA native query that returns two fields from my oracle database. The first field is a CHAR(2) field with two char values in it, like 'OZ' etc.
    The problem is, as soon as the query is executed it returns only first character of field1. If the actual value of field1 is like 'OZ' then it returns only 'Z'.
    Query nativeQueryForProfileInfo = getManager().createNativeQuery(queryToRun);
    List list = nativeQueryForProfileInfo.getResultList();
    Please help,
    thanks

    There could be several explanations here and it's difficult to say without having more details, possibilities are
    There is something wrong with your display logic.
    There is something wrong with your mapping.

  • What does or should "public function create(): Node"  return exactly?

    Seit gegrüsst
    I playing around with javafx for a project, evaluating this technology.
    When I'm displaying things on the screen through "CustomNodes" I have to override the "public function create(): Node" method.
    In examples found on google, there's often created a new Group or something like that and than be returned.
    Why can't I just return "this"?
    What does or should "public function create(): Node" return exactly? And why is this so?
    thx for response
    carpe noctem
    livevil
    Edited by: livevil on Oct 14, 2008 4:28 PM
    Edited by: livevil on Oct 14, 2008 4:29 PM

    "public function create(): Node" method should return a graphic
    representation of the class.
    For example, FunctionGraph class below draws a mathematical functiuon:
    import javafx.scene.*;
    import javafx.scene.paint.*;
    import javafx.scene.geometry.*;
    import javafx.scene.transform.*;
    import javafx.ext.swing.*;
    import java.lang.Math;
    import java.lang.System;
    public class FunctionGraph extends CustomNode{
        attribute scale:Number = 1;
        attribute xMin: Number;
        attribute xMax: Number;
        attribute dx: Number = 1;
        attribute color: Color;
        attribute func: function(a: Number):Number;
        public function create():Node{
          var n = (xMax - xMin) / dx;
          var polyline = Polyline{ stroke: color };
          for(i in [0..n]){
            var x = xMin + i * dx;
            var y =  (this.func)(x);
            insert(   x * scale ) into polyline.points;
            insert( - y * scale ) into polyline.points;  
          return Group{ content: [ polyline] };
    var w = 300;
    var h = 300;
    var xMin = -7;
    var xMax = 7;
    var dx = 0.05;
    var scale = 20;
    SwingFrame{
        width:  300
        height: 300
        title: "Function Graph"
        content: Canvas{
          content:  Group{
                transform: Translate.translate(w/2, h/2)
                content: FunctionGraph {
                    xMin: xMin
                    xMax: xMax
                    scale: scale
                    dx: dx
                    color: Color.BLUE
                    func: function(x:Number):Number{ return Math.sin(x); }               
        visible: true
    }

Maybe you are looking for

  • How do I "contract" my selection of contiguous files in the same direction (up and down) on Mac?

    In Windows, Mac OSX, and Bridge on Windows, when I hold SHIFT and navigate with up and down arrows, I can select more files or fewer files in the direction I am going. However, doing the same thing in Bridge CC on the Mac expands my selection on the

  • Flash Album Exporter in iFrame problem. Greybox not working as expected

    Hello all, I've searched and I can't find the solution or any info on the problem elsewhere. I've used Flash Album Exporter for the grey box effect. This appears perfectly here http://web.me.com/james.veitch/BoxReviews.index.html However, it's aligne

  • Video looks great on MBP, horrible when projected....

    I am projecting a video that I created in FinalCut on the MBP onto a screen using a Dell 1610X projector Check it out at http://accessories.us.dell.com/sna/products/HomeTheaterProjectors/productdetail.aspx?c=us&l=en&s=bsd&cs=04&sku=224-7541 During my

  • Userexit in delivery

    hello, friends. the requirement is that the delivery document should be output into a text file upon posting of goods issue.  my question, is their a userexit i can use for this purpose?  and also, should it be a userexit in the delivery or should it

  • Dg4odbc failure with MSSQL Driver

    Hi, I know that this subject has been discussed many times but I couldn't find one that would have helped me. My problem is the following : I have a Oracle 11gR2 platform on RedHat 6 and I need to get data from a SQL Server 2005 / 2008. To achieve th