Commit 8c1cde4ec3f060ef0ddeff634ce7aaa645044fd6

Authored by Chao Li(VISION)
1 parent ff2a78f5

Add C API qpdf_free_buffer to release memory allocated by stream data functions

include/qpdf/qpdf-c.h
... ... @@ -927,6 +927,14 @@ extern "C" {
927 927 QPDF_ERROR_CODE qpdf_oh_get_page_content_data(
928 928 qpdf_data qpdf, qpdf_oh page_oh, unsigned char** bufp, size_t* len);
929 929  
  930 + /* Call free to release the buffer allocated with malloc. This function can be used to free
  931 + * buffers that were dynamically allocated by qpdf functions such as qpdf_oh_get_stream_data
  932 + * or qpdf_oh_get_page_content_data. The caller is responsible for calling qpdf_free_buffer
  933 + * to manage memory properly and avoid memory leaks.
  934 + */
  935 + QPDF_DLL
  936 + void qpdf_free_buffer(unsigned char** bufp);
  937 +
930 938 /* The data pointed to by bufp will be copied by the library. It does not need to remain valid
931 939 * after the call returns.
932 940 */
... ...
libqpdf/qpdf-c.cc
... ... @@ -1772,6 +1772,16 @@ qpdf_oh_get_page_content_data(qpdf_data qpdf, qpdf_oh page_oh, unsigned char** b
1772 1772 }
1773 1773  
1774 1774 void
  1775 +qpdf_free_buffer(unsigned char** bufp)
  1776 +{
  1777 + QTC::TC("qpdf", "qpdf-c called qpdf_free_buffer");
  1778 + if (bufp && *bufp) {
  1779 + free(*bufp);
  1780 + *bufp = nullptr;
  1781 + }
  1782 +}
  1783 +
  1784 +void
1775 1785 qpdf_oh_replace_stream_data(
1776 1786 qpdf_data qpdf,
1777 1787 qpdf_oh stream_oh,
... ...
qpdf/qpdf-ctest.c
... ... @@ -1151,7 +1151,7 @@ test38(char const* infile, char const* password, char const* outfile, char const
1151 1151 assert(qpdf_oh_get_stream_data(qpdf, stream, qpdf_dl_none, 0, &buf, &len) == 0);
1152 1152 assert(len == 53);
1153 1153 assert(((int)buf[0] == 'x') && ((int)buf[1] == 0234));
1154   - free(buf);
  1154 + qpdf_free_buffer(&buf);
1155 1155  
1156 1156 /* Test whether filterable */
1157 1157 QPDF_BOOL filtered = QPDF_FALSE;
... ... @@ -1169,8 +1169,8 @@ test38(char const* infile, char const* password, char const* outfile, char const
1169 1169 assert(qpdf_oh_get_page_content_data(qpdf, page2, &buf2, &len) == 0);
1170 1170 assert(len == 47);
1171 1171 assert(memcmp(buf, buf2, len) == 0);
1172   - free(buf);
1173   - free(buf2);
  1172 + qpdf_free_buffer(&buf);
  1173 + qpdf_free_buffer(&buf2);
1174 1174  
1175 1175 /* errors */
1176 1176 printf("page content on broken page\n");
... ...
qpdf/qpdf.testcov
... ... @@ -626,6 +626,7 @@ qpdf-c stream data filtered set 1
626 626 qpdf-c stream data buf set 1
627 627 qpdf-c called qpdf_oh_get_page_content_data 0
628 628 qpdf-c called qpdf_oh_replace_stream_data 0
  629 +qpdf-c called qpdf_free_buffer 0
629 630 qpdf-c silence oh errors 0
630 631 qpdf-c called qpdf_oh_get_binary_string_value 0
631 632 qpdf-c called qpdf_oh_get_binary_utf8_value 0
... ...