CS010 Practice 5

C Strings and Dynamic Memory Management

  1. Write and test a function char *Concatenate(char *s1, char *s2) that takes two strings and returns a new string that is the concatenation of them. The function should allocate the memory for storing the new string with malloc.
  2. Write a program to see how much memory you can allocate before the computer runs out of space. malloc returns NULL when it cannot allocate the number of bytes requested, so one way to do this is to count how many blocks of 1000 bytes can be allocated before malloc returns NULL.
  3. What's wrong with this program? What happens when you compile and run it? (It will give you warning, but can still run the program)?
    char *copy(char *string) {
      char b[100];
      if (strlen(string) < 100) {
        strcpy(b, string); 
      } else {
        strcpy(b, "too big");
      }
      return b;
    }
    
    int main() {
      char *str = copy("moo cow moo");
      printf("%s\n", str);
      return 0;
    }
    


Return to CS 010 Home Page