-1

在我的函数中替换一个子字符串。如果输入子串比原始子串长,它会将输入串的一部分移出,为输入子串腾出空间。

我理解这会导致未定义的行为。我认为我应该能够使用 realloc() 分配所需的空间,但没有成功。

我尝试在 memmove() 之前添加这个:

char *newspc = (char*)realloc(in,len+sublen);
in = newspc;

这是一个合理的策略吗?为该操作腾出空间的正确方法是什么?

这是不使用 realloc() 的程序:

#include <iostream>
#include <string>
#include <string.h>

void replc(char* in, char* subin);

int main()
{
  char stmt[] = "replacing this $string ok";
  std::cout << stmt << "\n";
  replc(stmt, "longerstring");  //<<<4 characters longer breaks the program
  std::cout << stmt << "\n";

}

void replc(char* in, char* subin){
  uint8_t len = strlen(in);
  uint8_t aftok = strchr(strchr(in, '$'), ' ')-in;
  uint8_t dollar = strchr(in, '$')-in;
  uint8_t tklen = aftok - dollar;
  uint8_t sublen = strlen(subin);

   if(sublen <= tklen){
    //enough room for substring
    memmove(in+aftok-(tklen-sublen), in+aftok, (tklen-sublen)+1);
    memcpy(in+dollar, subin, sublen);
    in[len-(tklen-sublen)] = '\0';
   }
   else{
   //not enough room for substring
   // memory allocation should take place here?
    memmove(in+aftok+(sublen-tklen), in+aftok, (sublen-tklen)+1);
    memcpy(in+dollar, subin, sublen);
    in[len+(sublen-tklen)] = '\0';
   }

}
4

1 回答 1

1

首先,如果你想使用 realloc,你不必使用 memmove,因为 realloc 会负责复制数据。

来自男人:

realloc() 函数将 ptr 指向的内存块的大小更改为 size 字节。内容将在从区域开始到新旧大小的最小值的范围内保持不变。

此外,您只能对以前由 malloc、realloc 或 calloc 返回的指针使用 realloc

除非 ptr 为 NULL,否则它一定是由先前对 malloc()、calloc() 或 realloc() 的调用返回的。

所以你需要在你的 main 中使用 malloc

char *stmt = malloc(strlen("replacing this $string ok") + 1);
if (stmt)
    stmt = "replacing this $string ok";

其次,如果要更改调用函数中指针的值,则需要在该指针上使用指针(C 风格)或引用(C++ 风格),否则调用者中的指针将指向旧地址。

原型的 C 样式示例:

void replc(char** in, char* subin);

分配(NewSize 为整数):

*in = realloc(*in, NewSize);

(请记住,如果分配失败,malloc 和 realloc 可以返回 NULL)

于 2016-04-17T12:19:28.337 回答