gpt4 book ai didi

c - 修剪 char * 中的前 n 个字符并释放它

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:54 27 4
gpt4 key购买 nike

int length = 12;
char *filename;
char *key;

filename = (char *)calloc(length, sizeof(char));
strcpy(filename, "Hello World");//filename = "Hello World\0";

现在我想从左边修剪 5 个字符

key = filename + 6;
*(filename + 5) = 0;

free(filename);

printf("%s\n", key);
printf("%s\n", filename); //No Segmentation Fault Why??

我可以使用 memcpy 或 strcpy 实现此目的,但我可以通过上述方式实现吗?

最佳答案

这是错误的:

// So far so good...
filename = (char *)calloc(length, sizeof(char));
// No!!! You just leaked the previously allocated memory block!
// The `\0` at the end is also wrong.
filename = "Hello World\0";
// This is OK
key = filename + 6;
// You are writing into memory of a string literal, that's undefined behavior
*(filename + 5) = 0;
// You are freeing a string literal, that's undefined behavior too
free(filename);

至于没有段错误的部分,未定义的行为可能不会立即表现出来:例如,当您释放错误的区域时,释放本身可能有效,但后续分配可能会失败。

如果您想缩短字符串,制作一个副本并释放原始字符串:

char *filename = malloc(length);    // no cast
strcpy(filename, "Hello, world"); // no \0
char *trimmed = strdup(filename+6); // Make a copy
free(filename); // Free the original
filename = trimmed; // You are done!

一般来说,您只能释放您分配的内容。主要原因是 malloc/calloc/realloc store "bookkeeping" information在与返回给您的地址关联的内存中,通常在分配地址之前的 block 中。您可以尝试伪造它,但即使它有效,该解决方案也很脆弱且不可移植。

关于c - 修剪 char * 中的前 n 个字符并释放它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251772/

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