Thread: Problems with Malloc

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    6

    Problems with Malloc

    I'm trying to use malloc to increase the size of 3 dynamic arrays, but it keeps crashing as soon as it enters the first for loop. count is a pointer to an int holding the total nomber of records there should be, fname and lname are dynamic arrays holding names equal to count, and grades is another dynamic array holding the grades.

    Code:
     void addRecs(int *count, char **fname, char **lname, float *grades)
    {
    
      *count = *count + 1;
    
      //reallocate older stuff
      char **tempf = realloc(fname, *count * sizeof *tempf);
      for (int i = 0; i < *count - 1; i++) {
        tempf = realloc(fname, 20 * sizeof *tempf);
      }
    
      char **templ = realloc(lname, *count * sizeof *templ);
      for (int i = 0; i < *count - 1; i++) {
        templ = realloc(lname, 20 * sizeof *templ);
      }
      float *tempg = realloc(grades, *count * sizeof *tempg);
    
      //allocate space for newest
      templ[*count - 1] = (char *) malloc(20 * sizeof *lname[*count - 1]);
      tempf[*count - 1] = (char *) malloc(20 * sizeof *fname[*count - 1]);
    
      free(fname);
      free(lname);
      free(grades);
    
      fname = tempf;
      lname = templ;
      grades = tempg;
    
      printf("Add a record\n");
      scanf("%s %s %f", &fname[*count - 1][0], &lname[*count - 1][0],
            &grades[*count - 1]);
      int i;
      for (i = 0; i < *count; i++) {
        printf("First Name: %s, Last Name: %s, Score: %.2f \n", &fname[0],
               &lname[0], grades);
      }
    }
    Last edited by Salem; 04-09-2020 at 10:20 PM. Reason: removed eyebleed crayola

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. a couple of malloc problems
    By cAsk in forum C Programming
    Replies: 2
    Last Post: 04-18-2016, 12:20 AM
  2. Problems with malloc
    By Zachary Lewis in forum C Programming
    Replies: 7
    Last Post: 02-18-2008, 06:45 AM
  3. Problems with pointers and malloc()
    By Deirdre in forum C Programming
    Replies: 3
    Last Post: 10-28-2007, 04:20 PM
  4. malloc problems
    By garion in forum C Programming
    Replies: 5
    Last Post: 12-30-2005, 03:57 PM
  5. Malloc problems
    By PunkyBunny300 in forum C Programming
    Replies: 5
    Last Post: 10-01-2003, 07:27 PM

Tags for this Thread