-1

p1 pointer is used in other functions without any change. and when it is not needed any more free_stuffs function is called but when free_stuffs is called, I get double free or corruption (out) Aborted (core dumped)

char **someFunction(){
 const char ** p1 = (char **)malloc(total * sizeof(char *));
    for (int i = 0; i <= total; i++){
        *(p1 + i) = (char *)malloc(len * sizeof(char) +1);
    }
    return p1;
}
void free_stuffs(char ** p1){
   for (int i = 0; i <= total; i++){
      free(p1[i]);
   }
   free(p1);
}
user438383
  • 5,716
  • 8
  • 28
  • 43
PYigit
  • 74
  • 1
  • 5
  • Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) including the caller of the functions. – MikeCAT Jun 14 '22 at 12:44
  • Why use `*(p1 + i)` notation, when `p1[i]` is available? And the cast in `(char *)malloc(len * sizeof(char) +1)` is not necessary for `C` programming. This would result in a simpler to read: `p1[i] = malloc(len +1);` (`sizeof char` is always `1` by definition.) – ryyker Jun 14 '22 at 12:49
  • Where are `len` & `total` defined? – ryyker Jun 14 '22 at 12:55
  • `i <= total` -> `i < total`. Don't deviate from the canonical for loop form `for(size_t i=0; i – Lundin Jun 14 '22 at 13:05

1 Answers1

2

You are allocating only total elements, but using total+1 elements (0 to total).

Allocate enough elements to fix the error.

char **someFunction(){
 /* allocate total+1 elements instead of total */
 const char ** p1 = malloc((total + 1) * sizeof(char *));
    for (int i = 0; i <= total; i++){
        *(p1 + i) = malloc(len * sizeof(char) +1);
    }
    return p1;
}

Also note that casting results of malloc() family is considered as a bad practice.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70