I was surprised when gcc -Wall
compiled this without warning. Is this really legitimate C? What are the risks of writing code like this?
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
int b;
} MyStruct;
int main(void) {
MyStruct *s = malloc(sizeof(*s)); // as opposed to malloc(sizeof(MyStruct))
s->a = 5;
printf("%d\n", s->a);
}
ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
A NULL pointer doesn't allocate anything.
No, the two arrays are completely independent objects, that have nothing to do with each other, whatsoever.
Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable). integer, 8, stored. The other is the “value” or address of the memory location.
Not only it's legitimate, it's even preferable to the alternative. This way you let the compiler deduce the actual type instead of doing it manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With