【发布时间】:2015-11-29 10:41:27
【问题描述】:
我正在将此代码用于使用 pcre2 库的正则表达式替换:
PCRE2_SIZE outlengthptr=256; //this line
PCRE2_UCHAR* output_buffer; //this line
output_buffer=(PCRE2_UCHAR*)malloc(outlengthptr); //this line
uint32_t rplopts=PCRE2_SUBSTITUTE_GLOBAL;
int ret=pcre2_substitute(
re1234, /*Points to the compiled pattern*/
subject, /*Points to the subject string*/
subject_length, /*Length of the subject string*/
0, /*Offset in the subject at which to start matching*/
rplopts, /*Option bits*/
0, /*Points to a match data block, or is NULL*/
0, /*Points to a match context, or is NULL*/
replace, /*Points to the replacement string*/
replace_length, /*Length of the replacement string*/
output_buffer, /*Points to the output buffer*/
&outlengthptr /*Points to the length of the output buffer*/
);
但我似乎不明白如何正确定义 output_buffer 和指向它的长度 (outlengthptr) 的指针。
当我为outlengthptr 提供一个固定值时,该代码有效,但它保持不变,即它不会更改为output_buffer 的新长度。但是根据pcre2_substitue() specification应该改成output_buffer的新长度:
length、startoffset 和 rlength 值是代码单位,而不是字符,
outlengthptr指向的变量的内容也是如此,它会更新为新字符串的实际长度。
问题是:
- 当我将
outlengthptr设为固定值时,最终的字符串会以固定长度截断。 - 如果我不初始化变量
outlengthptr,我会遇到分段错误。
这是函数的原型:
int pcre2_substitute(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE startoffset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *mcontext, PCRE2_SPTR replacement, PCRE2_SIZE rlength, PCRE2_UCHAR *outputbuffer, PCRE2_SIZE *outlengthptr);
【问题讨论】:
-
好的,如果需要,请尝试分配 64k,调用,然后重新分配。
-
要获得最佳答案,请发帖MCVE
-
"当我将 outlengthptr 设为固定值时,最终的字符串将被截断为固定长度。" - 我会说这就是它应该如何工作的方式。如果您不希望输出被截断,则传递一个足够大以容纳整个输出的缓冲区。
-
@Jahid 不,不是。调用者负责管理输出缓冲区。
-
@Jahid:没有人粗鲁。我只是澄清了什么是真实的。您问:“如何初始化指向输出缓冲区长度的指针?”。好吧,你不能。指针没有像数组那样的长度属性(即 referenced 对象的长度)。根据您使用的语言,这里可能会有不同的答案。