c - 在 C 中使用 void 函数操作结构

标签 c memory memory-management struct

所以我被设置了一个任务,即创建一个人造字符串结构并在我的人造字符串结构上实现所有常用的字符串函数。我被困在名为append 的strcat 实现的测试中,第一个测试失败(段错误)是第5 行。我用于创建新结构的函数应该没问题,因为它通过了所有测试,但我将其包含在内只是为了以防万一。

我已经能够成功地为我的人造字符串结构实现长度、获取、设置和复制函数。

结构:

struct text {
    int capacity;
    char *content;
};

typedef struct text text;

我创建新结构的函数:

text *newText(char *s) {
    printf("new Text from %s\n", s);
    int sizeNeeded = (strlen(s)+1);
    int sizeGot = 24;
    while (sizeNeeded > sizeGot) {
        sizeGot = sizeGot * 2;
      }
    text *out = malloc(sizeGot);
    char *c = malloc(sizeGot);
    strcpy(c, s);
    out->content = c;
    out->capacity = (sizeGot);
    printf("the capacity is %d\n", sizeGot);
    return out;
    free(c);
}

我的附加功能:

void append(text *t1, text *t2) {
  printf("t1 content is %s, t2 content is %d\n", t1->content, *t2->content);
  int sizeNeeded = (t1->capacity + t2->capacity);
  int sizeGot = 24;
  while (sizeNeeded > sizeGot) {
      sizeGot = sizeGot * 2;
    }
  char *stringy = calloc(sizeGot, 32);
  stringy = strcat(t1->content, t2->content);
  free(t1);
  t1 = newText(stringy);
}

最后是测试:

void testAppend() {
    text *t = newText("car");
    text *t2 = newText("pet");
    append(t, t2);
    assert(like(t, "carpet"));
    assert(t->capacity == 24);
    text *t3 = newText("789012345678901234");
    append(t, t3);
    assert(like(t, "carpet789012345678901234"));
    assert(t->capacity == 48);
    freeText(t);
    freeText(t2);
    freeText(t3);
}

最佳答案

您分配内存的方式错误。您可以通过使用灵活的数组成员来解决这个问题,如下所示:

typedef struct {
  int capacity;
  char content[];
} text;

text *out = malloc(sizeof(text) + sizeof(something));
strcpy(out->content, str);
...

显然这样的代码是无意义的:

  return out;
  free(c);
}

启用编译器警告并听取它们。

关于c - 在 C 中使用 void 函数操作结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371504/

相关文章:

java方法重载为不同的方法共享相同的内存或不同的内存

c++ - 静态分配内存释放

c++ - 默认的 STL 分配器如何分配?

c - MPI MPI_REDUCE MPI MINLOC

c - 如何访问结构内部的 union ?

即使使用单元格缓存,PHPExcel 内存仍然耗尽 - 其他解决方案

c# - 我用 List<string> 遇到了 OutOfMemoryException - 这是限制还是我错过了什么?

c++ - 删除与删除[]

c++ - CMake 将文件复制到当前工作目录 Linux

字符 * 与字符 []