Questions 4

  1. Will these functions leak memory?
    void stat(){
    	double a[500];
    }
    
    void vla(size_t n){
    	double a[n];
    }
    
    void mal(){
    	double* a=(double*)malloc(500*sizeof(double));
    }
    
    void maf(){
    	double* a=(double*)malloc(500*sizeof(double));
    	free(a);
    }
    
    double* mar(){
    	double* a=(double*)malloc(500*sizeof(double));
    	return a;
    }
    
  2. Which lines, if any, of the following program will lead to compilation error?
    struct vector {double x,y,z;};
    struct vector v = {1,2,3};
    struct vector x = {1,2,3};
    struct vector a = [1,2,3];
    struct vector u = {.x=1,.y=2,.z=3};
    struct vector w = {.z=3,.y=2,.x=1};
    vector y;
    typedef struct vector vector;
    vector z;
    
  3. Which of the following Bash commands creates a list of '.c'-files in the current directory? Hint: redirection.
    ls *.c > cfiles.txt
    ls *.c 1> cfiles.txt
    ls *.c 2> cfiles.txt
    ls *.c &> cfiles.txt
    cat /dev/null > cfiles.txt; for i in *.c; do echo $i >> cfiles.txt; done
    
  4. Where does the following main function get its parameter from? That is, who calls the main-function and with which parameters?
    int main(int argc, char* argv[]) { /* do stuff */ }
    
  5. How can you convert a parameter of the main function into double or int number?
  6. What will the following program print?
    #include<stdio.h>
    #include<stdlib.h>
    double* foo(){ static double a[]={0,0,0}; return a; }
    int main(){
      double* a=foo(); a[2]=1;
      double* b=foo(); b[2]=2;
      printf("a[2] = %g\n",a[2]);
    return EXIT_SUCCESS;}
    
  7. What will the following program print?
    #include<stdio.h>
    #include<stdlib.h>
    double* foo(){ double* a=(double*)malloc(3*sizeof(double)); return a; }
    int main(){
      double* a=foo(); a[2]=1;
      double* b=foo(); b[2]=2;
      printf("a[2] = %g\n",a[2]);
      free(a);a=NULL;
      free(b);b=NULL;
    return EXIT_SUCCESS;}
    
  8. Can a C-structure contain a function? A pointer to a function?
  9. Which of the following lines is the correct declaration and why?
    struct f { int n; double *f(double); };
    struct g { int n; double (*f)(double); };
    
  10. Which of the two declarations is valid?
    #include<math.h>
    double (*f)(double) = sin;
    double (*g)(double) = &sin;
    
  11. With "f" from the (valid) declaration above, which of the following statements is valid?
    double y = f(1);
    double y = (*f)(1);
    
  12. What is the return value of the malloc function from stdlib.h?