Do I cast the result of malloc?

 

Yes, you should cast the result of malloc in C, but it's generally considered better practice to avoid casting the result of malloc in C++.

In C:

c
#include <stdio.h> #include <stdlib.h> int main() { int *ptr; ptr = (int *)malloc(sizeof(int)); // Casting the result of malloc if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } *ptr = 42; printf("Value at ptr: %d\n", *ptr); free(ptr); // Remember to free the allocated memory return 0; }

In C++, casting the result of malloc is not necessary and can even be harmful if you forget to include the <cstdlib> header. Instead, use new and delete for dynamic memory allocation in C++:

cpp
#include <iostream> int main() { int *ptr; ptr = new int; // No need to cast in C++ if (ptr == nullptr) { std::cout << "Memory allocation failed" << std::endl; return 1; } *ptr = 42; std::cout << "Value at ptr: " << *ptr << std::endl; delete ptr; // Remember to delete the allocated memory return 0; }

Keep in mind that in modern C++, using containers like std::vector or smart pointers like std::unique_ptr is often a safer and more convenient way to manage dynamic memory.

Comments