Thread: What is the issue with malloc?

  1. #1
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19

    What is the issue with malloc?

    Hi,

    I tried writing a code to manipulate text files (code below). I currently have a students.txt file. The goal of this code is to read in student information from the students.txt file and the entries that have students with a passing score should be copied over to a 2nd file, the students_temp.txt file.


    I am using microsoft visual c++ 2010 express, and the following issue occurs: the IDE detects an issue with malloc, and when I hover over it with my mouse, the following error message shows up:

    Code:
    "Error: a value of type "void*" cannot be used to initialize an entity of type "student"
    Also the output box shows some other errors (which I can list if necessary)


    I tried running exact same code using Code::Blocks and the Code Blocks ide does not have an issue and compiles perfectly fine. Why is that?

    I have both IDE's setup to be compiling "C" code and not "C++" and not sure if this matters or not but one other thing I noticed is that both softwares are using different compilers (Code Blocks was set to use GNU gcc and microsoft visual C++ uses the microsoft compiler.)

    I believe that malloc is being used in a valid way in my code as I have it written so not sure what is causing the issues


    Just wanted to use malloc to allocate some memory space to accommodate for currently unknown size (number of students that have passing score is unknown at this time and so I wanted to allocate enough space just in case, if that makes any sense)

    Thanks!!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct
    {
        char *name;
        float score;
    }student;
    
    
    int main()
    {
        FILE *originalFile;
        FILE* newFile;
    
    
        originalFile = fopen("D:\\Documents\\Visual Studio 2010\\Projects\\C\\Test\\edit_File\\edit_File\\students.txt", "r");
        newFile = fopen("D:\\Documents\\Visual Studio 2010\\Projects\\C\\Test\\edit_File\\edit_File\\students_temp.txt", "w");
    
    
        int studentCount;
        fscanf(originalFile, "%i", &studentCount);
    
    
        student *passingStudents = malloc(sizeof(student) * studentCount);
        fclose(originalFile);
        fclose(newFile);
    
    
        printf("Program ended. No error!\n");
        return 0;
    }
    Last edited by mc088; 02-11-2017 at 05:44 PM.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Is your file a .c or a .cpp file? I get a similar message using g++ on Linux.

    Please make sure you are compiling your source as a C program, NOT C++.

  3. #3
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19
    Yes, my code in a .c file, and yes, I am compiling C program, and not C++. (chose c project in code blocks, set the settings to compile as C in microsoft ide with the source file renamed as a .c file)

    Google search lead me to somebody else's similar question for which an answer of "The problem is that you're compiling C code with a C++ compiler. C allows that conversion from void * to an object pointer; C++ doesn't." was given.


    And so just wanted to know if I was using malloc properly is all, and also wanted to figure out what was making microsoft's compiler go haywire while the GNU GCC doesn't complain.

    Feels like it's an issue with the compiler being used (microsoft has issues code blocks with the GNU compiler doesn't for this code) Maybe I should just give up using microsoft compiler and just use the GNU compiler, if there's a good reason to do so.


    So the following complaints still given by microsoft compiler is thus if anybody wants to know:

    Code:
    1>------ Build started: Project: editFile, Configuration: Debug Win32 ------
    1>  editFile.c
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(21): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(22): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(24): error C2143: syntax error : missing ';' before 'type'
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(25): error C2065: 'studentCount' : undeclared identifier
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(27): error C2275: 'student' : illegal use of this type as an expression
    1>          d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(14) : see declaration of 'student'
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(27): error C2065: 'passingStudents' : undeclared identifier
    1>d:\documents\visual studio 2010\projects\c\test\editfile\editfile\editfile.c(27): error C2065: 'studentCount' : undeclared identifier
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    Last edited by mc088; 02-11-2017 at 11:22 PM.

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Copy/paste/compile the following in visual studio in a new project.
    Remember to set it for C.
    There's no significant changes, but try it anyway so we know exactly where we are.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    // Use single forward slashes instead of double backslashes 
    #define DIR "D:/Documents/Visual Studio 2010/Projects/C/Test/edit_File/edit_File/"
     
    typedef struct {
        char *name;
        float score;
    } Student;
    // struct names usually start with an uppercase letter
    
    int main()
    {
        FILE *originalFile = fopen(DIR "students.txt", "r");
        FILE *newFile = fopen(DIR "students_temp.txt", "w");
    
        int studentCount;
        // Use %d unless you really want to be able to read
        // octal and hex as well as decimal.
        fscanf(originalFile, "%d", &studentCount);
    
        Student *passingStudents = malloc(sizeof(Student) * studentCount);
    
        // ...
    
        free(passingStudents);
        fclose(newFile);
        fclose(originalFile);
     
        return 0;
    }

  5. #5
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19
    Hi algorism,

    I ran your code with both the Code Blocks and with the Visual C++ express 2010 and Code Blocks is happy but Visual C++ expresss 2010 has complaints.

    Screenshot of what I my screen looks like --> Screenshot by Lightshot

    The errors that I see are as follows:
    Code:
    1>------ Build started: Project: mallocTest, Configuration: Debug Win32 ------
    1>  mallocTest.c
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(15): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(16): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(21): warning C4996: 'fscanf': This function or variable may be unsafe. Consider using fscanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(253) : see declaration of 'fscanf'
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(23): error C2275: 'Student' : illegal use of this type as an expression
    1>          c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(10) : see declaration of 'Student'
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(23): error C2065: 'passingStudents' : undeclared identifier
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(27): error C2065: 'passingStudents' : undeclared identifier
    1>c:\users\mike\desktop\c\malloctest\malloctest\malloctest.c(27): warning C4022: 'free' : pointer mismatch for actual parameter 1
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    Last edited by mc088; 02-12-2017 at 12:02 AM.

  6. #6
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    To remove the "unsafe" warnings, add this as the very first line (before the includes) :
    Code:
    #define _CRT_SECURE_NO_WARNINGS
    I have no idea why it's giving the errors. There's nothing wrong with the code. For now, just continue with code blocks and hopefully someone will be able to give us an answer to the visual studio problem tomorrow.

    EDIT: Actually, now that I think about it, maybe it's being very strict and doesn't like that a variable declaration is mixed in with code. So try this:
    Code:
    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    
    #define DIR "D:/Documents/Visual Studio 2010/Projects/C/Test/edit_File/edit_File/"
     
    typedef struct {
        char *name;
        float score;
    } Student;
    
    int main() {
        FILE *originalFile;
        FILE *newFile;
        int studentCount;
        Student *passingStudents;
    
        originalFile = fopen(DIR "students.txt", "r");
        newFile = fopen(DIR "students_temp.txt", "w");
    
        fscanf(originalFile, "%d", &studentCount);
    
        passingStudents = malloc(sizeof(Student) * studentCount);
    
        // ...
     
        free(passingStudents);
        fclose(newFile);
        fclose(originalFile);
    
        return 0;
    }
    Last edited by algorism; 02-12-2017 at 12:50 AM.

  7. #7
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19
    Thanks for all the help Algorithm

    Testing out your new code after your EDIT, in visual studio compiler, there is no error shown in the output box. Console/CMD popups up normally as expected. However, ""Error: a value of type "void*" cannot be used to initialize an entity of type "student" on mouseover still exists. This time though, IDE highlighted the = sign before the malloc this time, where as in the code in my initial post, malloc was highlighted with the squiggly red underline.

    However ....
    If I replace
    Code:
    passingStudents = (Student*)malloc(sizeof(Student) * studentCount);
    with
    Code:
    passingStudents = malloc(sizeof(Student) * studentCount);
    in your newest code, then the Visual C++ express 2010 is happy with no red squiggly error message indicator at all. (However, it seems like that ERROR message and also doing that type casting is a C++ requirement, and not something to be done in C and to use your latest code as is without any change would be fine)

    Just guessing also, that the FILE pointer and the file initialization for the pointer should be on separate lines. (Sometimes I feel that MS likes to be cryptic on how they want things done lol xD )

    Lastly, would it be a good idea to continue with using Code Blocks? Seems like Visual C++ is mixing up C and C++ even though I'm telling it to compile as C?
    Last edited by mc088; 02-12-2017 at 01:59 AM.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Remember that Microsoft C is only C90.

    So no mixed declarations like this.
    Code:
        // octal and hex as well as decimal.
        fscanf(originalFile, "%d", &studentCount);
    
        Student *passingStudents = malloc(sizeof(Student) * studentCount);
    VS2010 is hopeless at C99, you're lucky you have // comments.
    VS2014 seems like the first hopeful, even then it's not a full deal.
    C99 acknowledged at last as Microsoft lays out its path to C++14 | Ars Technica
    c - Does Microsoft visual studio 2010 support c99? - Stack Overflow
    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.

  9. #9
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by mc088 View Post
    Hi algorism,

    I ran your code with both the Code Blocks and with the Visual C++ express 2010 and Code Blocks is happy but Visual C++ expresss 2010 has complaints.

    Screenshot of what I my screen looks like --> Screenshot by Lightshot
    Your Screenshot show on the left side a tree with source files and header files. In your project is a source file called 'stdafx.cpp' and a header file called 'stdafx.h'.
    I think Visual C++ express 2010 will comile allways as C++, because there is a cpp-file. Also the icon of both source file show 'c++'.
    If removing of 'stdafx.cpp' doesn't help, tray to create a new project and watch out all options in create dialog.
    Add only your 'mallocTest.c' in the new project.

    This is only a assumption, because i'm away from Microsoft Windows over 12 years.
    Hope it helps.
    Other have classes, we are class

  10. #10
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by mc088 View Post
    And so just wanted to know if I was using malloc properly is all, and also wanted to figure out what was making microsoft's compiler go haywire while the GNU GCC doesn't complain.

    Feels like it's an issue with the compiler being used (microsoft has issues code blocks with the GNU compiler doesn't for this code) Maybe I should just give up using microsoft compiler and just use the GNU compiler, if there's a good reason to do so.
    As @Salem has said:
    Remember that Microsoft C is only C90.
    gcc is both C99 and C11 complaint, plus it knows the difference between a C file, and a C++ file. Eliminating Microsoft, would cure the problem. The solution seems simple to me. ;^)

  11. #11
    Registered User mc088's Avatar
    Join Date
    Jan 2017
    Posts
    19
    Thanks everyone. I installed latest official Visual C++ express 2015 and uninstalled the old 2010 version. From what I read, Visual C++ express 2015 supports C++11, which should support most, if not 100% all, of C99, so I guess it should be able to handle the things that I am currently sorting out. [All codes from this thread compiled and ran without any issues on VC++ express 2015]

    So, I think I am fine now. I will keep Code Blocks as 2nd opinion just in case.
    Last edited by mc088; 02-12-2017 at 01:08 PM.

  12. #12
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by mc088 View Post
    So, I think I am fine now. I will keep Code Blocks as 2nd opinion just in case.
    Code::Blocks is an editor, or an IDE, NOT a compiler! Code::Blocks CALLS one of many compilers, whether it is an MS compiler, gcc, or many others.

    Code::Blocks FAQ:
    Q: What Code::Blocks is not?

    A: Code::Blocks is not a compiler, nor a linker. Release packages of Code::Blocks may include a compiler suite (MinGW/GCC), if not provided by the target platform already. However, this is provided "as-is" and not developed/maintained by the Code::Blocks development team.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-18-2015, 10:58 PM
  2. Malloc Pointer Issue
    By stefanturk in forum C Programming
    Replies: 2
    Last Post: 11-27-2012, 03:41 AM
  3. Serious issue with malloc function
    By anandvn in forum C Programming
    Replies: 14
    Last Post: 08-14-2010, 12:55 PM
  4. Replies: 6
    Last Post: 06-16-2008, 04:06 AM
  5. A bug I cannot see. . . malloc issue
    By Kennedy in forum C Programming
    Replies: 16
    Last Post: 09-26-2007, 09:49 AM

Tags for this Thread