Search code examples
cpointersglibc

Don't know why I get Glibc detected error


This is my function which causes the error

void copy_bounds_concrete(char* lower, char* upper, struct bounds* results){
   if (DEBUG)
      printf("%d %d \n", strlen(lower), strlen(upper));
   (*results).lowerBound =(char*) malloc(strlen(lower));
   strcpy((*results).lowerBound, lower);

   (*results).upperBound =(char*) malloc(strlen(upper));
   strcpy((*results).upperBound, upper);
}

and this is the struct bounds:

struct bounds
{
   char* name;
   char* lowerBound;
   char* upperBound;
}

I don't know why I got this pointer error. I have spent couple of hours to figure out but get nothing.


Solution

  • You have to add a +1 to all the strlen inside malloc, otherwise you don't allocate space for the string terminator (strlen returns the "logical length" of the string, not including the trailing NUL, so you allocate less memory than needed, which gives you that error).

    Incidentally, instead of (*result). you can do result->