gpt4 book ai didi

c - 我的程序对我的作业来说足够好,但我知道它不好

转载 作者:太空狗 更新时间:2023-10-29 16:23:10 24 4
gpt4 key购买 nike

我刚开始为 uni 分配作业,它向我提出了一个问题。

我不明白如何在不发生内存泄漏的情况下从函数返回字符串。

char* trim(char* line)  {
int start = 0;
int end = strlen(line) - 1;

/* find the start position of the string */
while(isspace(line[start]) != 0) {
start++;
}
//printf("start is %d\n", start);

/* find the position end of the string */
while(isspace(line[end]) != 0) {
end--;
}
//printf("end is %d\n", end);

/* calculate string length and add 1 for the sentinel */
int len = end - start + 2;

/* initialise char array to len and read in characters */
int i;
char* trimmed = calloc(sizeof(char), len);

for(i = 0; i < (len - 1); i++) {
trimmed[i] = line[start + i];
}
trimmed[len - 1] = '\0';

return trimmed;
}

如您所见,我正在返回一个指向 char 的指针,它是一个数组。我发现如果我尝试通过类似的方式制作“修剪过的”数组:

char trimmed[len];

然后编译器会抛出一条消息,指出该行需要一个常量。我认为这意味着出于某种原因您不能在初始化数组时使用变量作为数组长度,尽管有些事情告诉我这不对。

所以我改为通过为 char 指针分配一些内存来创建我的数组。

我知道这个函数对于它正在尝试做的事情来说可能不是最理想的,但我真正想知道的是:

  1. 您通常可以使用变量来初始化数组来声明长度吗:

    字符修剪[len];

  2. 如果我有一个该类型的数组 (char trimmed[]),它的返回类型是否与指向 char 的指针(即 char*)相同。

  3. 如果我通过分配一些内存并将其分配给 char 指针来创建我的数组,我该如何释放这 block 内存。在我看来,一旦我返回了这个数组,我就无法访问它来释放它,因为它是一个局部变量。

最佳答案

要解决 (3) - 完成后,您可以从调用代码中释放新分配的字符串:

char* tmp = trim(myline);

if (tmp != NULL) {
....
free( tmp );
}

但这会给调用者带来负担,让他们记住释放内存。因此,您可能会考虑将分配的缓冲区和缓冲区大小传递给 trim(),例如:

void trim(char* line, char *trimmed_buf, int trimmed_buf_len){ ... }

Neil 出色地解决了您的其他问题。基本上,数组声明 char trimmed[len]; 将在 stack 上声明一个局部变量,因此虽然返回 char * 在语法上是正确的> 对于这个内存,它指向的内存位置将不再有效。

关于c - 我的程序对我的作业来说足够好,但我知道它不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2525136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com