Lecture 020


freeing a pointer frees the memory the pointer points to. allocating a pointer allocate a memory in heap and return the address to the pointer


int *A = xmalloc(sizeof(int) * 5); allocates on heap


C99 Standard

C99 standard: out-of-bound are undefined behavior

Why undefined:

Aliasing into an Array

int *B = A+2

We are not allowed to free B

Casting Pointers

In C, you can cast any pointer to any other pointer type, never triggers an error.

Using int array as char array

Using int array as char array

But different computers stores int differently

Make sure castings are aligned: otherwise out-of-bound or undefined behavior

Casting int array to struct array

Casting int array to struct array

In C, void* is first element of any array.

two pointer with different type can be equal since pointers only store address, without element size.

Freeing an alias casting is allowed.

Casting to Char

Char has 8 bits (hhd), the smallest chunk of memory other than void*


Traditional Data Structure can only be heap-allocated

Allocating Array on Stack

int E[8] allocates on the stack int F[] = {2, 4, 6, 8, 10} They still have type int*

Allocating Struct on Stack

struct point p;
p.x = 9;
p.y = 7;

where p is not a pointer (there is no convenient way to initialize a struct in C99)

Capturing Memory Address

& operation can get address of


You cannot do:


char* s1 = "hello"; it is an char pointer (or char array if you like)


strlen: counts up to NUL, not included

strcpy(dst, src): copy up to NUL included

Different types of String

char *s1 = "hello" as TEXT segment

char *s2 = xcalloc(sizeof(char), strlen(char) + 1) as HEAP

char s3[] = "world"; char s4[] = {'s', '\0'}; char s5[5] as STACK

Summary of Undefined

Other undefined: (can be used to do security hacks)

Gain and Lost

Gain and Lost

Freeing Casted pointers

https://www.diderot.one/courses/42/post-office/30141 Freeing a casted non-void pointer is often undefined if they misaligned

Table of Content