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

Скачать или смотреть Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size

  • vlogize
  • 2025-09-17
  • 0
Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size
Why am I not getting the correct size after using malloc and printing using sizeof?
  • ok logo

Скачать Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size бесплатно в качестве 4к (2к / 1080p)

У нас вы можете скачать бесплатно Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size или посмотреть видео с ютуба в максимальном доступном качестве.

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

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

Cкачать музыку Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size бесплатно в формате MP3:

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

Описание к видео Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size

Discover why using `malloc` in C might not give you the size you expect when using `sizeof`. Learn how to correctly determine the size of memory allocated for a pointer.
---
This video is based on the question https://stackoverflow.com/q/29809898/ asked by the user 'Adarsh Rao' ( https://stackoverflow.com/u/4086221/ ) and on the answer https://stackoverflow.com/a/62233115/ provided by the user 'Kartikeya Gupta' ( https://stackoverflow.com/u/12879591/ ) 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: Why am I not getting the correct size after using malloc and printing using sizeof?

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 3.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.
---
Understanding Memory Allocation in C: Why sizeof Doesn't Match Expected Size

When working with dynamic memory allocation in C, particularly using the malloc function, you might encounter confusion regarding the size of the data being allocated versus what you see when you use the sizeof operator. One common question among programmers is: Why am I not getting the correct size after using malloc and printing using sizeof?

The Code in Question

Let's start with an example. Consider the following C code snippet:

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

The author expected the sizeof(*ptr) to output 80, as they allocated memory for an array of 10 integers. However, the output is 8. This discrepancy can be puzzling for many. Let's delve into the explanation.

Understanding sizeof and malloc

What malloc Does

The malloc function allocates a specified number of bytes in memory and returns a pointer to the beginning of this memory block. In this case, when you call malloc(10 * sizeof(integers)):

You are asking for enough memory to store 10 instances of the integers structure.

sizeof(integers) computes the memory required for one instance of the structure.

Analyzing sizeof(*ptr)

Now, let’s break down why sizeof(*ptr) gives you 8:

*ptr dereferences the pointer and accesses the first integers structure in the allocated memory.

In the above code, if integers is defined as having two int members, the size of this structure depends on the architecture but commonly would be 8 bytes (when int is 4 bytes and no padding is present).

Thus, sizeof(*ptr) gives you the size of one instance of integers, which is 8 bytes.

Why You Get 8 Instead of 80

When you print sizeof(*ptr) while you may expect it to return 80 (the total memory allocated), remember that sizeof is evaluating the type at the pointer’s dereference, not the total memory allocated by malloc.

If you want to see the total memory allocated for ptr, you have to calculate it using multiplication:

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

Size of the Pointer Itself

It's worth noting that when you call sizeof(ptr), you will also only get the size of the pointer itself, which is typically 8 bytes on 64-bit systems. This is because sizeof here computes the size of the pointer variable, not the size of the memory it points to.

Conclusion

Understanding how malloc and sizeof work in C can clear up a lot of confusion regarding memory management.

Use sizeof(*ptr) to determine the size of what the pointer points to.

Use multiplication to determine the total space allocated with malloc.

Remember that sizeof(ptr) returns the size of the pointer, not what it points to.

With these insights, you can manage memory in C more effectively and avoid common pitfalls when working with dynamic data structures.

Комментарии

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

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

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

video2dn Copyright © 2023 - 2025

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