brad = (Employee *)malloc(sizeof(Employee));
or brad = (struct person *)malloc(sizeof(struct person));
char name[20];
char first_name[10];
char last_name[20];
char *str_ptr;
_/ = checkmark
_/ name = str_ptr; (cannot assign a pointer to a statically allocated array)
str_ptr = name; (legal)
_/ if (name == "brad") { ... } (must use strcmp instead)
_/ name = "sue"; (must use strcpy instead)
_/ first_name = strdup("tom"); (cannot assign a pointer to a statically alocated array)
X strcpy(name, first_name); strcat(name, last_name); (The second strcat may write
past the end of name's memory)
name[10] = 'c'; (legal)
X str_ptr[10] = 'c'; (could be a write past str_ptr's memory, depending on the
size of the string currently pointed to by str_ptr)
--------------------
0xffbef974 double_int_ptr | 0xffbef978 |
0xffbef978 int_ptr | 0xffbef98c |
0xffbef97c string_ptr | 0xffbef980 |
0xffbef980 word | 'p' 'u' 'p' 'p' |
0xffbef984 word (continued) | 'y' '\0' ? ? |
0xffbef988 | ????? |
0xffbef98c count | 5 |
--------------------
s = 0xefffe4f8
i=0 x=0xefffe4f8 x=Plank *x=P x-s=0
i=1 x=0xefffe4f9 x=lank *x=l x-s=1
i=2 x=0xefffe4fa x=ank *x=a x-s=2
i=3 x=0xefffe4fb x=nk *x=n x-s=3
i=4 x=0xefffe4fc x=k *x=k x-s=4
s = 0xefffe4f0 i = 0 x=0xefffe4f0 *x=50 x-s=0 i = 1 x=0xefffe4f4 *x=51 x-s=1 i = 2 x=0xefffe4f8 *x=50 x-s=2 i = 3 x=0xefffe4fc *x=51 x-s=3 i = 4 x=0xefffe500 *x=50 x-s=4
Enter two words: Jim Plank Smaller is Jim Enter two words: Tee Martin Smaller is Martin Enter two words: Sammy Sosa Smaller is Sammy Enter two words: vols VOLS Smaller is VOLS Enter two words: VOLS VOLS Segmentation faultThe program seg faults on the last pair of words because smaller returns a null pointer. Hence when printf tries to de-reference the pointer to print the string it seg faults because it is de-referencing a null pointer.
Starting program: /home/bvz/courses/140/spring-2005/hw/testgdb x = 18 Program received signal SIGSEGV, Segmentation fault. 0x000106d0 in count (string=0xffbff6d0 "brad vander zanden") at testgdb.c:10 10 *x = strlen(string);
#0 0x000106d0 in count (string=0xffbff6d0 "brad vander zanden")
at testgdb.c:10
#1 0x00010790 in main () at testgdb.c:20
$1 = (int *) 0xffbff6d3