简体   繁体   中英

What causes double free or corruption (out) error?

Possible Duplicate: OpenCV double free or corruption (out): Aborted (core dumped)

I created a function that will receive image from client and use OpenCV in server to process image and return data. I have realized that I get this error only when I use function free() . Below is the code in my function.

// 2. Create Mat Image
Mat image = Mat::zeros(height, width, CV_8UC3);
uchar sockData[imageSize];

//Receive Image data here
printf("Receiving Image Data\n");
for (int i = 0; i < imageSize; i += bytecount)
{
   if ((bytecount = recv(*csock, sockData +i, imageSize - i, 0)) == -1)
   {
      fprintf(stderr, "Error receiving image %d\n", errno);
   }
}
// deallocate 
deallocateMemory(csock);

// Image Data Received, Now Reconstructing Image
printf("Image Data Received, Now Reconstructing\n");
int ptr = 0;
for (int i = 0; i < image.rows; i++)
{
  for (int j = 0; j < image.cols; j++)
  {
      image.at<cv::Vec3b>(i,j) = cv::Vec3b(sockData[ptr+0],sockData[ptr+1],
      sockData[ptr+2]);ptr = ptr + 3;
   }
}
// Write produced output to stdout - Print
printf("Image Processed, now Displaying Results...\n");
displayResultsOnConsole(results);

// free(sockData);
return 0;

The error appears when I uncomment free(sockData); Am I doing anything wrong?

You can only pass to free precisely the same pointer you got from malloc (or NULL , which does nothing). You break this rule, so bad things happen.

Uh. You allocate on stack and would want to deallocate on heap ?

You managed to add this big chunk allocated on stack ? -> no need to worry then.

Bad practice to allocate image bytes on stack because this is usually big. -> Allocate on heap, deallocate from heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM