CPE 357 C-Quiz + Midterm

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

21. Given an implementation of fw implemented (at the last minute, of course) using an ordinary binary tree and the two invocations: a) % fw /usr/dict/words /usr/man/*/* b) % fw /usr/man/*/* /usr/dict/words Which would you expect to complete its execution more quickly and why?

/usr/dict/words is in alphabetical order so the binary tree with /usr/dict/words first would just be a linked list and take longer to search through afterwards.

18. The stdio function getchar() reads a character from stdin and, on success, returns it. On failure, getchar() returns EOF which is defined to be −1. In spite of the fact that it's reading chars, getchar() returns an int. Why? (and explain)

256 possible bites. But there are 257 things that getchar() needs to return (256 bites and EOF). So getchar() returns bites as integers and -1 as EOF.

22. What is the meaning of a static declaration in C?

A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.

28. The C library function gets(): char **gets(char **s) reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. Even the man page says "Never use gets()." Why? What is the danger of using this function?

Buffer overflow vulnerability. Can never reach the '\0' and write into your memory. Can be done in a way that overwrites your memory with code that wrecks your programs.

20. Why is it important always to use the sizeof() operator when allocating space for a structure?

C compiler allows pad structures. So sizeof struct might be larger than the size of other ones (the sum of its components) because of padding.

16. While we're on the subject of macros, the C stdio library contains the following definitions: int fputc(int c, FILE *stream); int putc(int c, FILE *stream);

Each one writes a character to the given stream. The only difference between the two is that fputc() is guaranteed to be a function while putc() may be implemented as a macro. What is the purpose of having both? Macro is slightly faster (with modern computers and compilers doesn't really matter). So putc is a lot to be a macro, fputc exists because it needs to be a function i.e can pass pointers in.

19. What is the meaning of an extern declaration in C?

Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used to access variables across C files.

The Unix command df(1) reports the amount of free space available on a paticlar filesystem. Now, consider the following typescript: % df . Filesystem 1k-blocks Used Available Use% Mounted on /dev/hda1 46636 9034 35194 21% /extra % fortune > myfile myfile: No space left on device. % df(1) clearly shows 35Mb available on the disk. This isn't a lot of space, but surely it's enough for a fortune. Explain what has happened here.

Myfile cannot be created because there are no more inodes available.

The system call getpwent(2) allows a program to sequentially read through all the password information for all the users known to the system. It returns a pointer to a struct passwd. One of the fields of this struct is: char *pw passwd; /* user password */ Is this safe? Explain.

Safe because char *pw_passwd only stores a single character to act as a placeholder for the password which is now stored elsewhere and only accessible through the one way encrypted algorithms.

17. What's wrong with this picture? The comic below is amusing, but, unfortunately, incorrect. Why? "weird - my code's crashing when given pre-1970 dates" "epoch fail"

Unix time started on January 1 1970. time_t is signed so it can go backwards, so you can give pre-1970 dates.

A hard link can only be created to a file on the same disk partition, while a symbolic link can link any file anywhere. Why is this the case?

What is the difference between a symlink and hardlink? A symlink is an indirect pointer to a file. Hard links point directly to the inode of the file. Inodes change filesystem to filesystem so a hard link has to reside on the file system.

If process owned by root receives a SEGV while its current working directory is a user's home directory, the corefile will wind up in that directory: % ls -l ~ -rw------- 1 root root 22945792 Mar 13 2005 core.13411 . . . Explain why—even with the ownership and permissions as shown above—the user will always be able to remove this inconvenient corefile.

Yes, you can unlink it to rm it. You own your own directory so you can rewrite on it.

Is it possible for a user to use open(2) or creat(2) to create a file s/he cannot delete? Explain how this is possible or why it is not possible.

You need have write and execute permissions to delete a file and to create a file you need those same permissions on the directory. So it is not possible to create a file you cannot delete.

A programmer dissatisfied with the behavior of a C library function can redefine it without limiting the capabilities of the program. (That is, there is nothing the program could have done before the redefinition that it could not do afterwards.) A system call, however cannot be replaced without limiting the program. Why is this?

You need special permissions to replace system calls without limiting the program. There is no way to mimic a system call because we cannot interact with the kernel the same way it does.

32. A novice programmer wrote the following fragment of code for a new game destined to be a mega- hit. At the next code review, the project manager looked at the program, announced, "I will not be responsible for this kind of work!" and quit on the spot (in today's economy, no less!) [...] void ask the question(NODE node) { char *question; char c; /* build the query */ question=strcat("Is it ",node−>str); /* print the query */ printf("%s?",question); c = get answer(); [...] } What is wrong with the code fragment? (Hint: It compiles fine, and you don't have to make any assumptions about any other code.)

strcat() does not allocate memory. Thus when concatenating the string the new string will be written into unallocated memory. Then segfault. Note this will surely happen because the first argument is a literal string "Is it " that only has enough space allocated for that, rather than a pointer for which we don't know how much space is allocated.

8. People learning the C language often say that "arrays and pointers are the same thing." This is a common misconception, but like many misconceptions, there is an element of truth to it. (a) State one common property of arrays and pointers. (b) State one significant difference between arrays and pointers.

(a) Both pointers and arrays can be indexed. The name of an array is the address of the first element of the array. (b) A pointer can be an lvalue. (it can be changed) An array name is a constant.

Given a UNIX filesystem composed of several smaller filesystems (different disk partitions, e.g.), why would you expect using mv to move a file to another directory on the same partition to be faster than moving it to a directory on another partition?

Because on the same file system, you have to change to symlink. On other, you have to copy everything over and delete the original file.

It is not possible to make a hard link on one disk partition (filesystem) to a file that resides on another partition. Given what you know about links (and setting aside the question of whether this would be a good idea in the first place) explain why such a thing must be impossible.

Hard links point to inodes, inodes in different file systems will never be the same so you could never make a link to another file system because it would never find the corresponding inode.

It is possible (trust me) for there to be a file that a user can move within a filesystem, but not across filesystems. Assuming the user has write permission for both the source and destination directories, how (under what circumstances) could this be?

If all the inodes allocated in the other filesystem are being used then there is no inode for the file you are trying to move.

Some versions of the finger(1) command output "New mail received. . . " and "Unread since. . . " with the corresponding dates and times. Given that user's mail is stored in /var/mail/user, how can the program determine these times and dates?

If mail is a file you could stat it and check the access and modified time for each file to determine the time and dates.

Anyone can make a hard link to a file, but only root is permitted to make hard links to a directory. What is the danger in creating a hard link to a directory?

If you could create a hardlink to a directory, you could create a hardlink that points from child to parent which would mess up the structure of the file system, only root can make hard links to a directory because its parent is itself.

23. It is said, "Never include anything in a header file that either allocates memory or defines (rather than declares) a function." Why would this be a problem?

If you instantiate a header file twice then the variables are instantiated twice.

The command ls -lc shows the change time (ctime) for a file. Given the following sequence of commands, why does removing file cause link's ctime to change? % fortune > file % ln file link % ls -lc file link -rw-------. 2 pnico pnico 44 Nov 3 21:55 file -rw-------. 2 pnico pnico 44 Nov 3 21:55 link ...some time later ... % date Tue Nov 3 21:56:59 PST 2009 % rm file % ls -lc link -rw-------. 1 pnico pnico 44 Nov 3 21:57 link %

Link points to the inode of file, when file is removed, the inode of file is updated so ctime is changed and since link points to the inode, the ctime of inode is modified.

Is it possible for an ordinary user (not root) to create a file owned by some other user id? How about another group id? Why or why not?

No, because UID and GID are taken from the entry into the password file when logging in and will be unique to the user

If you forget the password to your hornet account and the sysadmin refuses to tell you what it was, is he just being lazy? Why or why not?

Password: the way to get a password is a one way algorithm so you can't get it back if you don't have the password the sysadmin would only able to change the password.

What is the difference between a program and a process?

Process: an instance of a computer program that is being executed. Program: a sequence of instructions, written to perform a specified task with a computer.

Consider the following two programs: ****Program A**** #include <unistd.h> #include <stdio.h> /* Macro SIZE is defined at compile-time */ int main(int argc, char *argv[]){ int n; char buffer[SIZE]; while((n=read(STDIN FILENO,buffer,SIZE))>0) { write(STDOUT FILENO,buffer,n); } return 0; } ****Program B**** #include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]){ int c; while( EOF != (c=getchar()) ) putchar(c); return 0; } Program A was compiled once with SIZE defined to be 1 and a second time with SIZE defined to be 8192. Program B was compiled as is. The resulting executables, in random order, were named larry, curly, and moe. Exp. Command (min:sec) — % ls -l BigFile -rwx------ 1 pnico pnico 42114758 Oct 2 2002 BigFile 1 % larry < BigFile > /dev/null --- 0:00.04 2 % curly < BigFile > /dev/null --- 0:01.88 3 % moe < BigFile > /dev/null --- 2:06.90 Given this information, match each of the program configurations below to the proper executable and explain why. (The reason is worth more than the identification.)

Program A, SIZE = 1. Executable: Moe. System calls are slower and time consuming. Small buffer means more system calls. Program A, SIZE = 8192. Executable: Larry. Less system calls occurring. Also less looping. Program B. Executable: Curly. Less costly because no system calls are involved. Calling one thing at a time however is time costly.

The utime(2) system call allows one to set the last access and last modification times on a file to any representable time (very useful for sneaking in late homeworks), but it cannot backdate the last changed time (bummer!). Why not?

Since utime() alters the access and modification types which are metadata, changed time would be updated at the end of the process so there would be no way to backdate the last-changed time.

In a Unix system, is it possible for there to be a file that the owner of the file cannot remove? Why or why not?

Someone check this answer pls and thankz. If you are the root user and change the permissions of the directory (or move to directory you don't have permissions) you can be locked out of your own directory.

27. Unix system calls (and many other C functions) return zero to indicate success and a non-zero value to indicate failure. Given that zero in C is interpreted as false and non-zero is interpreted as true, this convention seems misguided. Give one good reason why it is a good idea to do it this way.

Success 0 doesn't need anymore information, non-zero can tell you what kind of failure.

Lab02 2. Is it possible in C to declare and initialize a pointer that points to itself? Why or why not? (And, if so, how, of course.)

Sure, but you won't be able to get it to typecheck (because the pointer to whatever type will be a pointer to that type). You can do it with void *, though: void *p = &p;

If symlinks are so much more flexible than hard links, what is the use of having hard links at all?

Symlinks harder to keep track of because if a file is deleted, but then a file of the same name is elsewhere, the system won't know that it's a different file so it would link you to there which is the incorrect file. Hard links would not too this because the inodes would be different.

What is the fundamental difference between a system call and a library function?

System calls are functions provided by the kernel, while library functions are within program libraries. Example: fopen() vs. open(). We call fopen() from header file in a C program. Programming environment will call system call open() from kernel and perform its file opening task. After executing, control flow return to user mode.

The Unix command df(1) reports the amount of free space available on a particular filesystem. Now, consider the following typescript: % df . Filesystem 1k-blocks Used Available Use% Mounted on /dev/hda1 46636 8856 35372 21% /extra % ls -l [...] -rw------- 1 pnico pnico 52428751 Feb 19 20:26 testfile [...] % df(1) clearly shows the disk capacity to be 45.5MB, yet testfile occupies 50MB of disk space according to ls(1). Has the the storage management problem finally been solved by writing the bits really small? Explain what is really happening here.

Testfile has holes in it which aren't written to disk just kept track of where they are, so although the file is 50MB it occupies less disk space.

Lab02 7. A subcase of Ex. 2.2 from Stevens: On unix5, what is the actual data type of a size t (the type of malloc(3)'s argument)? In what header file is it defined?

The answer depends on various configuration parameters, but you'll find that it's either an unsigned int or an unsigned long.

33. In ANSI C, the const qualifier can be applied to a variable declaration to indicate that its value will not be changed. Consider the following two function prototypes for error-handling routines: char *strerr(int errnum) return string describing error code void perror(const char *s); print a system error message In these two prototypes, perror()'s parameter has the const attribute, while strerr()'s does not. Why?

The argument to perror(3) is a pointer. The const attribute guarantees that the called routine will not change the characters to which it points, guaranteeing that perror(3) will not alter the string passed to it. The parameter of strerror(3) is an int. Since C is call-by-value, all strerror(3) gets is a copy, so the caller already knows that errnum will not be altered.


Kaugnay na mga set ng pag-aaral

MACRO MIDTERM 1&2 + FINAL PRACTICE

View Set

Municipal Bond Programs in Georgia

View Set

Muscular Dystrophy Practice Questions

View Set

Equations of Parallel and Perpendicular Lines: Assignment

View Set

Certified Ethical Hacker v10 Practice Exam

View Set

HESI RN Case Study - Cystic Fibrosis Peds

View Set