Logo video2dn
  • Сохранить видео с ютуба
  • Категории
    • Музыка
    • Кино и Анимация
    • Автомобили
    • Животные
    • Спорт
    • Путешествия
    • Игры
    • Люди и Блоги
    • Юмор
    • Развлечения
    • Новости и Политика
    • Howto и Стиль
    • Diy своими руками
    • Образование
    • Наука и Технологии
    • Некоммерческие Организации
  • О сайте

Скачать или смотреть Understanding Why the new Keyword Works While malloc Doesn't in C+ +

  • vlogize
  • 2025-09-28
  • 0
Understanding Why the new Keyword Works While malloc Doesn't in C+ +
C++ why does new keyword works and malloc does not?c++pointersmallocnew operator
  • ok logo

Скачать Understanding Why the new Keyword Works While malloc Doesn't in C+ + бесплатно в качестве 4к (2к / 1080p)

У нас вы можете скачать бесплатно Understanding Why the new Keyword Works While malloc Doesn't in C+ + или посмотреть видео с ютуба в максимальном доступном качестве.

Для скачивания выберите вариант из формы ниже:

  • Информация по загрузке:

Cкачать музыку Understanding Why the new Keyword Works While malloc Doesn't in C+ + бесплатно в формате MP3:

Если иконки загрузки не отобразились, ПОЖАЛУЙСТА, НАЖМИТЕ ЗДЕСЬ или обновите страницу
Если у вас возникли трудности с загрузкой, пожалуйста, свяжитесь с нами по контактам, указанным в нижней части страницы.
Спасибо за использование сервиса video2dn.com

Описание к видео Understanding Why the new Keyword Works While malloc Doesn't in C+ +

Explore the distinctions between the `new` operator and `malloc` in C+ + . Understand memory initialization and its impact on your code.
---
This video is based on the question https://stackoverflow.com/q/63638955/ asked by the user 'GreenVoice' ( https://stackoverflow.com/u/13197361/ ) and on the answer https://stackoverflow.com/a/63639021/ provided by the user 'Mureinik' ( https://stackoverflow.com/u/2422776/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: C+ + why does new keyword works and malloc does not?

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
C+ + Memory Management: The Difference Between new and malloc

When diving into C+ + , you may come across two ways to allocate memory: the new keyword and the malloc function. While they might seem similar at first glance, they behave differently, especially when it comes to memory initialization. Today, we'll explore this problem and clarify why the new keyword works seamlessly while malloc can lead to unexpected results.

The Problem Explained

Consider the following simple program that creates an instance of a structure using the new keyword:

[[See Video to Reveal this Text or Code Snippet]]

This program works perfectly, printing the value 400 as expected. However, when you attempt to allocate memory using malloc, like this:

[[See Video to Reveal this Text or Code Snippet]]

You may encounter a surprising and incorrect output, such as -842150451. Why does this happen? Let’s break it down.

Understanding new vs malloc

The new Keyword

Memory Allocation and Initialization: The new keyword not only allocates memory for an object but also calls its constructor. In the case of your testStructure, the initializer values are set for members a, b, and c directly.

Automatic Type Casting: new automatically casts to the type of the pointer, so there's no need for explicit type casting.

Automatic Memory Management: With new, the memory allocated for the object can be efficiently deallocated using delete.

The malloc Function

Memory Allocation Only: In contrast, malloc simply allocates a block of memory without initializing it. This means that the values for a, b, and c remain uninitialized and could hold random data from memory.

Explicit Type Casting Required: The result of malloc needs to be cast to the appropriate type since it returns a void*.

No Constructor Calls: With malloc, constructors are not called, leading to potential undefined behavior when trying to access uninitialized values.

The Undefined Behavior of Uninitialized Memory

When you use malloc for your structure, the int c field is not set to 400 as expected. Instead, it might still contain whatever garbage value happens to be in that memory space, leading to that confusing output you noticed.

Here’s What Happens Step-by-Step:

Memory for testStructure is allocated with malloc. Memory is allocated, but no initialization occurs.

When attempting to print testStruct->c, you are reading from uninitialized memory, resulting in undefined behavior.

Just because the memory is allocated doesn't mean it has meaningful values.

Conclusion

In summary, always remember to consider how memory allocation works in C+ + . For classes and structures with non-trivial constructors (like your testStructure), always use the new keyword to ensure proper initialization. malloc can easily lead to hard-to-debug issues due to uninitialized memory. Understanding these differences can help you write more reliable and bug-free C+ + code.

When in doubt, trust new for managing memory the C+ + way!

Комментарии

Информация по комментариям в разработке

Похожие видео

  • О нас
  • Контакты
  • Отказ от ответственности - Disclaimer
  • Условия использования сайта - TOS
  • Политика конфиденциальности

video2dn Copyright © 2023 - 2025

Контакты для правообладателей [email protected]