Search code examples
c++pointersmallocnew-operator

C++ why does new keyword works and malloc does not?


I'm learning about pointers and structures and I ran into this hard to understand the problem for me. I have created this simple program for testing purpose:

#include <iostream>

struct testStructure
{
    int a = 0;
    int b = 0;
    int c = 400;
};

int main()
{
    struct testStructure* testStruct;
    testStruct = new testSctructure;

    std::cout << testStruct->c;

    delete testStruct;
    return 0;
}

the above program works just fine, it prints the value 400. But when i try to do it with malloc:

#include <iostream>

struct testStructure
{
    int a = 0;
    int b = 0;
    int c = 400;
};

int main()
{
    struct testStructure* testStruct;
    testStruct = (testStructure*)malloc(sizeof testStructure);

    std::cout << testStruct->c;

    free(testStruct);
    return 0;
}

it gives me this value: -842150451

Why? The above examples were written and build in Visual Studio 2019.

I know that in C++ you should almost always want to use new keyword but I wanted to experiment a bit.


Solution

  • new initializes the allocated memory with the class' constructor (which is implicit in this this case).

    malloc performs no initialization, it just allocates a portion of memory. Reading uninitiazlied memory will have undefined behavior.