Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory with an undefined pointer

Tags:

c

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);
}
like image 800
countunique Avatar asked Apr 24 '14 20:04

countunique


People also ask

How do you allocate memory using pointer?

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.

Does NULL pointer allocate memory?

A NULL pointer doesn't allocate anything.

Can we dynamically allocate memory without pointers?

No, the two arrays are completely independent objects, that have nothing to do with each other, whatsoever.

Can we dynamically allocate memory to pointer?

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.


1 Answers

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.

like image 108
SomeWittyUsername Avatar answered Oct 24 '22 16:10

SomeWittyUsername