Thread: malloc Causes Warnings in MSVC++

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    204

    malloc Causes Warnings in MSVC++

    I have the following code
    Code:
    #include <stdio.h>
    
    int main(){
    	double *a;
    
    	a = malloc(4*sizeof(double));
    	free(a);
    
    	return 0;
    }
    It produces the warning messages
    warning C4047: '=' : 'double *' differs in levels of indirection from 'int'
    I tried to cast the the value that a is set to by changing the code to this
    Code:
    #include <stdio.h>
    
    int main(){
    	double *a;
    
    	a = (double*)malloc(4*sizeof(double));
    	free(a);
    
    	return 0;
    }
    but then I get the message
    warning C4312: 'type cast' : conversion from 'int' to 'double *' of greater size
    Is it possible to code this so that MSVC++ doesn't give me warning messages? GCC never seems to gives me any complaints. If C++ is really a superset of C, why does this not compile with G++?

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You're missing stdlib.h... Consider turning up the warning level for your compiler.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You should also see the FAQ on why casting malloc is bad, because of all the mistakes you can hide by doing so (failure to include the right header files, compiling C code with a C++ compiler).

    > If C++ is really a superset of C,
    It's been a long time since this was true.
    http://david.tribble.com/text/cdiffs.htm
    C++ is a semantic superset, but that doesn't mean that every valid C program is also a valid C++ program.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM