Thread: cast malloc() WHY?.

  1. #1
    Unregistered
    Guest

    cast malloc() WHY?.

    /* Why is the cast (char *) needed for malloc, this is ansi c not old kernigan */
    /* and richie but I get an error saying cannot convert void to char without the */
    /* cast (borland compiler, win 95 operating system) */

    #include<stdio.h>
    #include<string.h>
    #include<alloc.h>
    #include<process.h>
    #include<conio.h>

    int main(void)
    {
    char *str; /* Character pointer */

    /* malloc returns a pointer to a block of memory or NULL */
    if ((str=(char *)malloc(6)) == NULL) /* mallocs returned pointer is void */
    { /* A void pointer can be assigned to a pointer variable of any object type */
    printf("Not enough memory to allocate buffer\n");
    exit(1);
    }

    strcpy(str, "Hello");

    printf("String is %s\n", str);

    free(str);
    getch();
    return 0;
    }

    /* Thanks guys */

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    The malloc function return is undefined (or void type). Malloc does not take into account the type of data you are creating space for, therefore the return is cast into a form that fits the type of pointer you are assigning to it.

    Void is not the same as NULL, it simply means undefined.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    With the current standard of C, malloc shouldn't be cast. Many are the times it will hide other errors in your program if you do.

    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    You're getting an error because it's compiling as C++ code. In C, you don't have to cast malloc. In C++, you do.
    Callou collei we'll code the way
    Of prime numbers and pings!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Should I cast return value of malloc?
    By movl0x1 in forum C Programming
    Replies: 12
    Last Post: 05-30-2007, 10:22 AM
  2. Including The Right DLLs
    By bumfluff in forum Game Programming
    Replies: 8
    Last Post: 12-28-2006, 03:32 AM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. errors in class(urgent )
    By ayesha in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2001, 10:14 PM
  5. errors in class(urgent)
    By ayesha in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2001, 06:51 PM