Skip to content

Commit

Permalink
adding segfault code
Browse files Browse the repository at this point in the history
  • Loading branch information
yqh committed Sep 10, 2019
1 parent 71a4d94 commit b91d2dd
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lab1/starter/segfault/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
CC=gcc
CFLAGS=-Wall -g
LD=gcc
LDFLAGS=-g


OBJS=main_segv.o

all: main_segv.out

main_segv.out: $(OBJS)
$(LD) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS)

.c.o:
$(CC) $(CFLAGS) -c $<

.PHONY: clean
clean:
rm -f *.o *.out
1 change: 1 addition & 0 deletions lab1/starter/segfault/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The sample code demonstrates a segmentation fault.
43 changes: 43 additions & 0 deletions lab1/starter/segfault/main_segv.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @brief: To demonstrate segmentation fault
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct buf {
size_t size; /* buffer size */
char *data ; /* data */
};

/* To model a point on 2D terminal screen */
struct point
{
int x;
int y;
};


int main(void)
{
struct buf *p, *q;
struct point pt={1,2};

p = (struct buf *)malloc(sizeof(struct buf));
q = p;

p->data = (char *)&pt ;
p->size = sizeof(struct point);

printf("p->x = %d, p->y =%d\n", ((struct point*)(p->data))->x, ((struct point *)(p->data))->y);

/* remove pointe p */
p->data = NULL;
p->size = 0;
free(p);

printf("q->x = %d, q->y =%d\n", ((struct point*)(q->data))->x, ((struct point *)(q->data))->y);


return(0);
}

0 comments on commit b91d2dd

Please sign in to comment.