Remember that C and C++ are actually completely different languages. They share some common syntax, but C is a procedural language and C++ is object oriented, so they are different programming paradigms.

gcc should work just fine as a C compiler. I believe MinGW uses it. It also has flags you can specify to make sure it's using the right version of C (e.g. C99).

If you want to stick with C then you simply won't be able to use new (it's not part of the C language) but there shouldn't be any problems with moving to C++ for a shared library, just so long as you put your Object Oriented hat on when you do.

I'd suggest you just stick with the language you are more comfortable with. The fact that you're using new suggests that will be C++, but it's up to you.

Answer from Cameron Skinner on Stack Overflow
Top answer
1 of 7
9

Remember that C and C++ are actually completely different languages. They share some common syntax, but C is a procedural language and C++ is object oriented, so they are different programming paradigms.

gcc should work just fine as a C compiler. I believe MinGW uses it. It also has flags you can specify to make sure it's using the right version of C (e.g. C99).

If you want to stick with C then you simply won't be able to use new (it's not part of the C language) but there shouldn't be any problems with moving to C++ for a shared library, just so long as you put your Object Oriented hat on when you do.

I'd suggest you just stick with the language you are more comfortable with. The fact that you're using new suggests that will be C++, but it's up to you.

2 of 7
4
  1. You can use e.g. GCC as a C compiler. To ensure it's compiling as C, use the -x c option. You can also specify a particular version of the C standard, e.g. -std=c99. To ensure you're not using any GCC-specific extensions, you can use the -pedantic flag. I'm sure other compilers have similar options.

  2. malloc and calloc are indeed how you allocate memory in C.

  3. That's up to you.* You say that you want to be cross-platform, but C++ is essentially just as "cross-platform" as C. However, if you're working on embedded platforms (e.g. microcontrollers or DSPs), you may not find C++ compilers for them.

  4. No, new and delete are not supported in C.


* In my opinion, though, you should strongly consider switching to C++ for any application of non-trivial complexity. C++ has far more powerful high-level constructs than C (e.g. smart pointers, containers, templates) that simplify a lot of the tedious work in C. It takes a while to learn how to use them effectively, but in the long run, they will be worth it.
🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 62449-new-keyword.html
'new' keyword - C Board - Cprogramming.com
MyClass var1 = MyClass(constructorarg); Now what the new keyword does is dynamicly allocate memory for an object on the heap, and then return the ADDRESS to that location. Now what you need to do if you want to do this, is use a pointer (something you didn't deal with dirrectly in Java) here is an example
🌐
Cppreference
en.cppreference.com › w › cpp › keyword › new.html
C++ keyword: new - cppreference.com
Log in · Page · Discussion · View · Edit · History · From cppreference.com · < cpp‎ | keyword · C++ [edit] C++ language · [edit] Keywords · [edit] new expression · allocation functions as the name of operator-like functions · Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/new&oldid=175035" Support us ·
Top answer
1 of 15
101

Your observations are correct. C++ is a complicated beast, and the new keyword was used to distinguish between something that needed delete later and something that would be automatically reclaimed. In Java and C#, they dropped the delete keyword because the garbage collector would take care of it for you.

The problem then is why did they keep the new keyword? Without talking to the people who wrote the language it's kind of difficult to answer. My best guesses are listed below:

  • It was semantically correct. If you were familiar with C++, you knew that the new keyword creates an object on the heap. So, why change expected behavior?
  • It calls attention to the fact that you are instantiating an object rather than calling a method. With Microsoft code style recommendations, method names start with capital letters so there can be confusion.

Ruby is somewhere in between Python and Java/C# in it's use of new. Basically you instantiate an object like this:

f = Foo.new()

It's not a keyword, it's a static method for the class. What that means is that if you want a singleton, you can override the default implementation of new() to return the same instance every time. It's not necessarily recommended, but it's possible.

2 of 15
91

In short, you are right. The new keyword is superfluous in languages like Java and C#. Here are some insights from Bruce Eckel who was a member of C++ Standard Committee in 1990s and later published books on Java:

[T]here needed to be some way to distinguish heap objects from stack objects. To solve this problem, the new keyword was appropriated from Smalltalk. To create a stack object, you simply declare it, as in Cat x; or, with arguments, Cat x("mittens");. To create a heap object, you use new, as in new Cat; or new Cat("mittens");. Given the constraints, this is an elegant and consistent solution.

Enter Java, after deciding that everything C++ is badly done and overly complex. The irony here is that Java could and did make the decision to throw away stack allocation (pointedly ignoring the debacle of primitives, which I've addressed elsewhere). And since all objects are allocated on the heap, there's no need to distinguish between stack and heap allocation. They could easily have said Cat x = Cat() or Cat x = Cat("mittens"). Or even better, incorporated type inference to eliminate the repetition (but that -- and other features like closures -- would have taken "too long" so we are stuck with the mediocre version of Java instead; type inference has been discussed but I will lay odds it won't happen. And shouldn't, given the problems in adding new features to Java).

Top answer
1 of 12
386

Method 1 (using new)

  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

Method 2 (not using new)

  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Some easy cases:

  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new
2 of 12
135

There is an important difference between the two.

Everything not allocated with new behaves much like value types in C# (and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true). More precisely, objects allocated without using new have automatic storage duration Everything allocated with new is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.

Anything allocated on the stack has to have a constant size, determined at compile-time (the compiler has to set the stack pointer correctly, or if the object is a member of another class, it has to adjust the size of that other class). That's why arrays in C# are reference types. They have to be, because with reference types, we can decide at runtime how much memory to ask for. And the same applies here. Only arrays with constant size (a size that can be determined at compile-time) can be allocated with automatic storage duration (on the stack). Dynamically sized arrays have to be allocated on the heap, by calling new.

(And that's where any similarity to C# stops)

Now, anything allocated on the stack has "automatic" storage duration (you can actually declare a variable as auto, but this is the default if no other storage type is specified so the keyword isn't really used in practice, but this is where it comes from)

Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically. By contrast, anything allocated on the heap has to be manually deleted by you. Here's an example:

void foo() {
  bar b;
  bar* b2 = new bar();
}

This function creates three values worth considering:

On line 1, it declares a variable b of type bar on the stack (automatic duration).

On line 2, it declares a bar pointer b2 on the stack (automatic duration), and calls new, allocating a bar object on the heap. (dynamic duration)

When the function returns, the following will happen: First, b2 goes out of scope (order of destruction is always opposite of order of construction). But b2 is just a pointer, so nothing happens, the memory it occupies is simply freed. And importantly, the memory it points to (the bar instance on the heap) is NOT touched. Only the pointer is freed, because only the pointer had automatic duration. Second, b goes out of scope, so since it has automatic duration, its destructor is called, and the memory is freed.

And the barinstance on the heap? It's probably still there. No one bothered to delete it, so we've leaked memory.

From this example, we can see that anything with automatic duration is guaranteed to have its destructor called when it goes out of scope. That's useful. But anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of arrays. That is also useful. We can use that to manage our memory allocations. What if the Foo class allocated some memory on the heap in its constructor, and deleted that memory in its destructor. Then we could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything to be on the stack.

And that is pretty much exactly how most C++ code works. Look at the standard library's std::vector for example. That is typically allocated on the stack, but can be dynamically sized and resized. And it does this by internally allocating memory on the heap as necessary. The user of the class never sees this, so there's no chance of leaking memory, or forgetting to clean up what you allocated.

This principle is called RAII (Resource Acquisition is Initialization), and it can be extended to any resource that must be acquired and released. (network sockets, files, database connections, synchronization locks). All of them can be acquired in the constructor, and released in the destructor, so you're guaranteed that all resources you acquire will get freed again.

As a general rule, never use new/delete directly from your high level code. Always wrap it in a class that can manage the memory for you, and which will ensure it gets freed again. (Yes, there may be exceptions to this rule. In particular, smart pointers require you to call new directly, and pass the pointer to its constructor, which then takes over and ensures delete is called correctly. But this is still a very important rule of thumb)

🌐
cppreference.com
en.cppreference.com › w › c › keyword.html
C keywords - cppreference.com
This is a list of reserved keywords in C. Since they are used by the language, these keywords are not available for re-definition.
🌐
Reddit
reddit.com › r/learnprogramming › what does the "new" keyword do in programming?
r/learnprogramming on Reddit: What does the "new" keyword do in programming?
March 6, 2016 -

Sometimes people choose to write "new" before declaring an array or calling a function. But there are some who say it is bad and people should do without it.

But... If you can do without "new", why do people use it in the first place? Everyone talks about pros vs cons but no one talks about what is this "new" and what purpose does it serve.

Top answer
1 of 5
4
new is used to allocate an object with dynamic storage duration, while declaring an object without new uses automatic storage duration. Given an example: Obj foo(); Obj* bar = new Obj(); foo is allocated using automatic storage duration. foo will exist only within the scope of the brackets containing the declaration. When the block ends, the foo will be destructed. bar is allocated using dynamic storage duration. It will persist even when you go out of scope. That means if you exit the block bar is currently in, e.g. you finish your function and return elsewhere, bar will still continue to exist. You have to manually destruct it yourself using the delete or delete[] where appropriate. The rule of thumb is for every new and new[] in your code, there should exist an equal number of delete and delete[]. This is one of the most common beginner bugs, as new users allocate memory dynamically but forget to call delete after they are done, assuming their object will be destructed automatically. This is not the case, and can lead to memory leaks.
2 of 5
3
The behavior of new is not the same across languages so you'll need to let us know which language you're interested in. Briefly: In C++ new allocates memory. There are several different new operators in this language each with a different purpose but in general it's possible to avoid their use by using containers from the standard library or - when necessary - one of the smart pointer classes. The reason to avoid new is that it must be paired with a corresponding delete. Forgetting to do so leaks memory. In Java and C# new allocates a new object. This is similar to C++ but objects in these languages are garbage collected. There is no corresponding delete operator because the object is automatically cleaned up after there are no longer any references to the object. It is perfectly fine - and necessary - to use new in these languages. In JavaScript new allocates a new object and sets up that object's prototype chain in a particular way. As in Java and C# these objects are garbage collected. The new operator is different in behavior from Java or C# because its behavior can be implemented using other language constructs; that is, new is syntactic sugar which saves you from writing some code. In particular, you can already allocate an object by simply declaring it.
🌐
Javiercasas
javiercasas.com › articles › the-tyranny-of-the-new-keyword-1
The Tyranny of the new keyword (I)
Every modern programming language has a way to construct new values, because every minimally complex program is designed to process basic values into more complex results. The usual operation to summon creating a new value is the new keyword, at least in Java-like languages, such as Java, C++, C#, TypeScript and others.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › new-vs-operator-new-in-cpp
new vs operator new in C++ - GeeksforGeeks
February 21, 2023 - The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer ...
🌐
Quora
quora.com › What-are-some-alternatives-to-using-the-new-keyword-in-C
What are some alternatives to using the 'new' keyword in C++? - Quora
Answer: In C++ you can call a function that creates objects and returns them. The compiler is an optimizing compiler, and will arrange the code to not need to return a copy in most cases. [code]#include #include #include #include using st_vec = st...
🌐
IBM
ibm.com › docs › en › wdfrhcw › 1.4.0
C reserved keywords
We cannot provide a description for this page right now
🌐
Quora
quora.com › What-exactly-does-the-keyword-new-do-in-C++-During-an-interview-I-said-it-instantiates-a-class-and-calls-the-constructor-Why-is-that-wrong
What exactly does the keyword new do in C++? During an interview, I said it instantiates a class and calls the constructor. Why is that wrong? - Quora
Answer (1 of 13): In summary [code ]new[/code] allocates memory for the specified object from the free-store and then initializes the object (if primitive) or calls the relevant constructor (if a class object). In C++ classes aren’t themselves objects (like Java say) and while any static members...
🌐
Quora
quora.com › What-is-the-purpose-of-the-new-operator-in-C
What is the purpose of the 'new' operator in C++? - Quora
Answer: In C++, [code ]new[/code] is really a number of different things (at least 3 and maybe more depending on how you count things). First Form Probably the most common use of new, especially among beginners is something like: [code ]Foo *bar = new Foo;[/code] Many experienced C++ programmer...
🌐
Scaler
scaler.com › topics › cpp › new-operator-in-cpp
new Operator in C++ - Scaler Topics
June 27, 2022 - In contrast, variables created at compile time exist in the stack memory segment. If sufficient memory is available, the new operator allocates the memory and returns a pointer to the first byte of the allocated memory block. When an object is created using the new keyword following things happen:
🌐
Bitesizedengineering
bitesizedengineering.com › p › what-happens-when-you-type-the-new
What happens when you type the "new" keyword?
February 9, 2023 - The first one is, you guessed it, operator new, and it’s job is to find a place to house your bits, and the second one is placement new, which actually CONSTRUCTS the object in the memory space returned by operator new.
🌐
Cplusplus
cplusplus.com › forum › beginner › 24413
"new" keyword - C++ Forum
In C++, that use is optional and you have to explicitly declare it as a pointer, cell* c1. Your example should be cell* c1 = new cell;
🌐
PREP INSTA
prepinsta.com › home › c++ online tutorials › new keyword in c++
New keyword in C++ programming language | Prepinsta
February 16, 2023 - New: The new keyword in C++ allocates the required bytes of memory by returning a pointer to the allocated memory
🌐
W3Schools
w3schools.com › c › c_ref_keywords.php
C Keywords
C Examples C Real-Life Examples C Exercises C Quiz C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... A list of useful C keywords can be found in the table below.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › keywords › new-modifier
new modifier - C# reference | Microsoft Learn
It is an error to use both new and override on the same member, because the two modifiers have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden.