程序代写代做代考 data structure compiler CS241 hw0 Tianwei Xu NetID:txu25 Chapter 1

CS241 hw0 Tianwei Xu NetID:txu25 Chapter 1
 Hello World (System call style)
o Write a program that uses write() to print out “Hi! My name is “.
#include
#include
int main() {
write(1,”Hi! My name is David.\n”,22);
return 0;
}
 Hello Standard Error Stream
o Write a program that uses write() to print out a triangle of height n to Standard Error
o* o **
 n should be a variable and the triangle should look like this for n = 3
***
#include
#include
int main() {
int i,j;
int n=3;
for(i=1;i<=n;i++){ for(j=1;j<=i;j++){ write(2,"*",1); } write(2,"\n",1); } return 0; }  Writing to files o Take your program from "Hello World" and have it write to a file  Make sure to to use some interesting flags and mode for open()  man 2 open is your friend #include
#include
#include
#include
#include
int main() {
mode_t mode = S_IRUSR | S_IWUSR | S_IRWXU;
int fildes = open(“output.txt”,O_CREAT | O_TRUNC | O_RDWR, mode); write(fildes,”Hi! My name is David.\n”,22);
close(fildes);
return 0;
}
 Not everything is a system call
o Take your program from “Writing to files” and replace it with printf()
#include
#include
#include
#include
#include
int main() {
mode_t mode = S_IRUSR | S_IWUSR | S_IRWXU;
int fildes = open(“output.txt”,O_CREAT | O_TRUNC | O_RDWR, mode); printf(“Hi! My name is David.\n”);
close(fildes);
return 0; }
o Name some differences from write() and printf()

1. write() is a system call. printf() is not a system call.
2. Their syntax are different.
3. prinf() can have format specifiers.
4. write() can choose where to write, while printf() can only print to
buffer.
Chapter 2
There are least 8 bits in a byte. But it varies in different machines. o How many bytes is a char?
Char is defined to take one byte.
 Not all bytes are 8 bits?
o How many bits are there in a byte?
o Tell me how many bytes the following are on your machine: int, double, float, long, long long
Sizeof(int)=4 sizeof(double)=8 sizeof(float)=4 sizeof(long)=8 sizeof(long long)=8
 Follow the int pointer
o On a machine with 8 byte integers:
 int main(){
 int data[8];
}
If the address of data is 0x7fbd9d40, then what is the address of data+2?
The address of data+2 is : 0x7fbd9d50
o What is data[3] equivalent to in C? data[3] is equivalent to 3[data] and *(data+3)

 sizeof character arrays, incrementing pointers
Remember the type of a string constant “abc” is an array.
o Why does this segfault?
Because constant string can’t be changed.
o What does sizeof(“Hello\0World”) return? It returns 12.
o What does strlen(“Hello\0World”) return? It returns 5.
o Give an example of X such that sizeof(X) is 3 X=”ab”
char *ptr = “hello”; *ptr = ‘J’;
o Give an example of Y such at sizeof(Y) might be 4 or 8 depending on the machine.
Y= long Chapter 3
 Program arguments argc argv
o Name me two ways to find the length of argv
1. length = argc+1;
2. loop and accumulate until argv[i] == NULL
o What is argv[0] argv[0] is the program name.

 Environment Variables
o Where are the pointers to environment variables stored?
environ
 String searching (Strings are just char arrays)
o On a machine where pointers are 8 bytes and with the following code:
 char *ptr = “Hello”;
char array[] = “Hello”;
What is the results of sizeof(ptr) and sizeof(array)? Explain why.
Sizeof(ptr) = 8. Because sizeof a pointer is the space a pointer takes which is 8 in the machine.
Sizeof(array) = 6. Because sizeof an array is the actual space the array takes, which is 6 in this problem, including the tailing 0.
 Lifetime of automatic variables
o What datastucture is managing the lifetime of automatic variables?
The data structure is stack. Chapter 4
 Memory allocation using malloc, heap and time
o If I want to use data after the lifetime of the function it was created in, then where should I put it and how do I put it there?
You should use malloc to access heap memory.
Int *x = malloc(sizeof(int));
o Fill in the blank. In a good C program: “For every malloc there is a ___”. For every malloc there is a free.
 Heap allocation Gotchas

o Name one reason malloc can fail. There is not enough heap memory.
o Name some differences between time() and ctime()
time() returns seconds since 1970, and take the parameter NULL. ctime() returns formatted char array, and takes *timep
o What is wrong with this code snippet?
 free(ptr);
free(ptr);
You can’t free a pointer twice. If you free a non-null pointer a second time, this behavior is undefined. You may have a segmentation fault, or some other unexpected problems.
o What is wrong with this code snippet?
o How can one avoid the previous 2 mistakes?
free(ptr);
printf(“%s\n”, ptr);
If you use a freed pointer, you may get garbage because that memory may have been used by others.
Set pointer to NULL immediately after freeing a pointer. i.e free(ptr); ptr = NULL;
 struct, typedefs and a linked list
o Create a struct that represents a Person and typedef, so that “struct Person” can be replaced with a single word.
 A person should contain the following information: name, age, friends (pointer to an array of pointers to People).

o Now make two persons “Agent Smith” and “Sonny Moore” on the heap who are 128 and 256 years old respectively and are friends with each other.
#include
#include
#include
struct Person{
char* name;
int age;
struct Person** friends;
};
typedef struct Person person_t;
int main() {
person_t* person1=(person_t*)malloc(sizeof(person_t)); person_t* person2=(person_t*)malloc(sizeof(person_t)); person1->name=”Agent Smith”;
person2->name=”Sonny Moore”;
person1->age=128;
person2->age=256;
person1->friends = (person_t**)malloc(sizeof(person_t*)); *(person1->friends)= person2;
person2->friends = (person_t**)malloc(sizeof(person_t*)); *(person2->friends)=person1;
free(person1->friends);
free(person2->friends);
free(person1);
free(person2);
return 0;
}
 Duplicating strings, memory allocation and deallocation of structures
o Create functions to create and destroy a Person (Person’s and their names should live on the heap).
 create() should take a name and make a copy of the name and also an age. Use malloc to reserve sufficient memory. Be sure initialize all fields (why?).
 destroy() should free up not only the memory of the person struct but also free all its attributes that are stored on the heap (the array

if it exists and the string). Destroying one person however should not destroy any others.
person_t* person_create(char* name,int age,person_t* friends){ person_t* result = (person_t*)malloc(sizeof(person_t)); result -> name = strdup(name);
result -> age = age;
result -> friends = (person_t**)malloc(sizeof(person_t*)); *(result->friends) = friends;
return result;
}
void person_destroy(person_t* p){
free(p->friends);
free(p->name);
memset(p,0,sizeof(person_t));
free(p);
p=NULL; }
Chapter 5
 Reading characters, Trouble with gets
o What functions can be used for getting characters for stdin and writing them to stdout?
Getting character: getchar(), gets() Wrting to stdout : putchar(),puts()
o Name one issue with gets()
If the input is larger than the size of the buffer, it will cause buffer overflow, which may change the content of other variables.
 Introducing sscanf and friends
o Write code that parses a the string “Hello 5 World” and initializes 3 variables to (“Hello”, 5, “World”) respectively.

#include
#include
int main() {
char* a= “Hello 5 World”;
char first_part[20];
int i;
char second_part[20];
int result = sscanf(a,”%s %d %s”,first_part,&i,second_part);
return 0; }
 getline is useful
o What does one need to define before using getline()?
A char pointer as a buffer, and set it to NULL. A size_t integer as capacity, and set it to 0.
o Write a C program to print out the content of a file line by line using getline()
//suppose output.txt exists in “/home/user” #define _GNU_SOURCE
#include
#include
int main(){
char* buffer = NULL;
size_t capacity =0;
FILE *fp;
ssize_t result;
fp = fopen(“/home/user/output.txt”,”r”);
while( (result = getline(&buffer,&capacity,fp)) !=-1 ){
printf(“%s\n”,buffer);
}
free(buffer);
return EXIT_SUCCESS;
}

C Development (A web search is useful here)
 What compiler flag is used to generate a debug build? -g
Because you have to write the flag for make such as make debug.
 Are tabs or spaces used in Makefiles? Tabs.
 What are the differences between heap and stack memory?
 Are there other kinds of memory in a process?
Environment, program arguments, code constants, global variables …
 You modify the makefile to generate debug builds and type make again. Explain why this is insufficient to generate a new build.
Stack is used for static memory allocation, while heap is used for dynamic memory allocation. When you use heap memory, you have to free it yourself. But you don’t have to free stack memory.

APPENDDIX: Codes for Chapter1-Chapter5
/*Write your C code here*/
#include
#include
#include
#include
#include
int main() {
int count,count2;
write(1,”Hi! My name is David.\n”,22);
for(count=1;count<=3;count++){ for(count2=1;count2<=count;count2++){ write(2,"*",1); } write(2,"\n",1); } mode_t mode = S_IRUSR | S_IWUSR; int fildes = open("output.txt",O_CREAT | O_TRUNC | O_RDWR, mode); write(fildes,"Hi! This is David in a file.\n",29); printf("Hi! This is David in a file.\n"); close(fildes); write(STDOUT_FILENO,"HELLO\n",6); write(STDERR_FILENO,"Again!\n",7); return 42; } /*Write your C code here*/ #include
#include #include
int main() {
printf(“Char is %d bits\n”,CHAR_BIT); printf(“sizeof(int) is %d\n”,sizeof(int)); printf(“sizeof(double) is %d\n”,sizeof(double)); printf(“sizeof(float) is %d\n”,sizeof(float)); printf(“sizeof(long) is %d\n”,sizeof(long)); printf(“sizeof(long) is %d\n”,sizeof(long long)); int data[8];
printf(“data is at %p\n”,data);
printf(“data+1 is at %p\n”,data+1); printf(“data+2 is at %p\n”,data+2);
*(data) = 100;
*(data+1) = 101;
data[2]=102;
2[data]=102;//crazy way
//char* ptr = “hello”; printf(“%d\n”,sizeof(“Hello\0World”)); printf(“%d\n”,strlen(“Hello\0World”)); printf(“%d\n”,sizeof(“ab”));
return 0;

}
/*Write your C code here*/
#include
extern char** environ;
void change(char*);
char* find(char*);
void f1(int level){
char array[]=”f1f1″;
printf(“f1 : %p\n”,array);
if(level) f1(level-1);
}
void f2(){
char array[]=”f2f2″;
printf(“f2 : %p\n”,array);
}
void eg(){
char blah[1024];
f1(5); }
int main(int argc, char* argv[]) { printf(“argv[0]=%s\n”,argv[0]); printf(“argv[argc]=%s\n”,argv[argc]); int acc=0;
while(argv[acc]!= NULL){
acc++;
}
printf(“%d\n”,acc);
printf(“argc = %d\n”,argc);
int count=1;
int sum=0;
for(;count
#include
#include
#include
//time_t time(time_t *t)
//char *ctime(const time_t *timep)
static char array[256];
struct Link{
int value;
struct Link* next;
};
struct Link2{
char* key;
char* value;
struct Link2* next;
};
struct Person{
char* name;
int age;
struct Person** friends;
};
typedef struct Person person_t;
person_t* person_create(char* name,int age,person_t* friends){
person_t* result = (person_t*)malloc(sizeof(person_t)); result -> name = strdup(name);
result -> age = age;
result -> friends = (person_t**)malloc(sizeof(person_t*)); *(result->friends) = friends;
return result;
}
void person_destroy(person_t* p){
free(p->friends);
free(p->name);

memset(p,0,sizeof(person_t));
free(p);
p=NULL;
}
typedef struct Link link_t;
typedef struct Link2 link2_t;
link_t one;
int value;
char* currenttime(){
char* result = malloc(128);
if(!result) return result;
time_t secondsSince1970 = time(NULL);
char* timeASCII = ctime( &secondsSince1970); //strcpy(result,”10:26 AM”); strcpy(result,timeASCII);
return result;
}
link2_t* link_create(char* akey, char* avalue){
printf(“creating link %s -> %s \n”,akey,avalue); link2_t* result = (link2_t*)malloc(sizeof(link2_t)); result -> key = strdup(akey);
result -> value = strdup(avalue);
return result;
}
void link_destroy(link2_t*p){
free(p->key);
free(p->value);
memset(p,0,sizeof(link2_t));
free(p);
}
link2_t* root;
int main() {
char* ptr=currenttime();
printf(“%s\n”,ptr);
free(ptr); ptr = NULL;
one.value = 42;
one.next = & one;
link_t* ptr1=(link_t*)malloc(sizeof(link_t)); link_t* ptr2=(link_t*)malloc(sizeof(link_t)); ptr1->value = 42;
ptr2->value = 43;
ptr1->next = ptr2;
ptr2->next = NULL;
free(ptr1);
free(ptr2);
person_t* person1=(person_t*)malloc(sizeof(person_t)); person_t* person2=(person_t*)malloc(sizeof(person_t)); person1->name=”Agent Smith”;
person2->name=”Sonny Moore”;
person1->age=128;
person2->age=256;
person1->friends = (person_t**)malloc(sizeof(person_t*)); *(person1->friends)= person2;
person2->friends = (person_t**)malloc(sizeof(person_t*));

*(person2->friends)=person1;
free(person1->friends);
free(person2->friends);
free(person1);
free(person2);
return 0; }
/*Write your C code here*/
#define _GNU_SOURCE
#include
#include
int main(int argc,char** argv) {
/*
int c=0x10203040;
printf(“%x\n”,c);
/*
while((c = getchar())!= EOF ){
if(c>=32) c=c ^ 1;
putchar(c);
//printf(“%c %d %x\n”,c,c,c);
}
char buffer[12];
gets(buffer);
printf(“%x\n”,c); puts(buffer);//printf(“%s\n”,ptr);
char * data = “Lawrence_VERY_LONG_NAME_ANGRAVE 20″; char buffer[20];
int score = -42;
//int result = sscanf(data,”%19s %d”,buffer, & score); //int result = fscanf(stdin,”%19s %d”,buffer, & score); //int result = scanf(“%19s %d”,buffer, & score); //printf(“Result :%d, %s : %d\n”,result,buffer,score); char* a= “Hello 5 World”;
char first_part[20];
int i;
char second_part[20];
int result = sscanf(a,”%s %d %s”,first_part,&i,second_part); printf(“%d : %s :%s :%d\n”,result,first_part,second_part,i); */
char* buffer = NULL;
//ssize_t getline(char **lineptr, size_t *n, FILE *stream); size_t capacity = 0;
ssize_t result= getline(&buffer, &capacity,stdin); if(result>0 && buffer[result-1]==’\n’){
buffer[result-1]=0;
}
printf(“%d : %s\n”,result ,buffer);
free(buffer);
return EXIT_SUCCESS;
} /*c

//suppose output.txt exists in “/home/user” #define _GNU_SOURCE
#include
#include
int main(){
char* buffer = NULL;
size_t capacity =0;
FILE *fp;
ssize_t result;
fp = fopen(“/home/user/output.txt”,”r”);
while( (result = getline(&buffer,&capacity,fp)) !=-1 ){ printf(“%s\n”,buffer);
}
free(buffer);
return EXIT_SUCCESS;
}
*/