-2

In c++, I have a server code running continuously 24*7 but i am getting segfault sometimes while freeing the buffer. I tried try catch as well.

        try {
                    free(partialBuf);
                } catch (...) {
                    printf("Caught partial buf free error");
                }

Thanks in advance!

Kritpal Singh
  • 475
  • 5
  • 10

3 Answers3

0

A segfault is not an exception in the sense of other C++ exceptions, hence you cannot catch it with try/catch. A segfault can have any number of reasons, but in 99.9% of cases it's a memory access bug :-) If the segfault happens during a call to delete or free(), chances are that you are having a double-free issue.

Community
  • 1
  • 1
edgar.holleis
  • 4,803
  • 2
  • 23
  • 27
0

You could use GDB to debug, and find out whether you are trying to free a pointer which was not allocated previously.

DesirePRG
  • 6,122
  • 15
  • 69
  • 114
0

Since you're apparently able to use try/catch, you're writing C++ code. It helps to know which language you're using.

The solution then is to use std::shared_ptr. You may have multiple places in which a pointer goes out of scope. With shared_ptr you no longer call free, and as a bonus shared_ptr will call delete only once (after the last pointer goes out of scope).

However, you should now allocate memory with new instead of malloc.

MSalters
  • 173,980
  • 10
  • 155
  • 350