realloc在收缩块时不起作用,仅在扩展[已关闭]时起作用

dfuffjeb  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(141)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
2天前关闭。
Improve this question

void dstring_truncate(DString *destination, unsigned int truncatedLength) {
    assert(destination != NULL);
    assert(*destination != NULL);
    assert(truncatedLength >= 0);

    DString *tempstring = destination;
    *tempstring = realloc(*destination, truncatedLength);

    destination[truncatedLength] = '\0';
}

这个函数得到指针和truncatedLength的地址,当前字符串的长度是25,destination和tempstring都有"invalid characters in string",当我把truncatedLength改成比destination大的时候,两个都指向正确的字符串。
我尝试添加一个空终止,但它不工作,当我尝试*destination[truncatedlength] = '\0'它也不工作,即使它是一个双指针。

2lpgd968

2lpgd9681#

  1. destination[truncatedLength] = '\0';是UB,因为你写的是分配的内存之外的值。你也试着写一个从整数'\0'转换而来的指针。这不是双指针的工作方式。
    Dstring只是我定义的一个类型。
    1.不要隐藏typedef后面的指针
  2. tempstring的用法完全错误,毫无意义。
    1.使用正确的尺寸类型
    1.为了使函数与n字符串函数一致,truncatedLength是一个whilo字符串长度,包括空终止字符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *dstring_truncate(char **destination, size_t truncatedLength)
{
   assert(destination != NULL);
   assert(*destination != NULL);
   assert(truncatedLength > 0);

   char *tempstring;
   tempstring = realloc(*destination, truncatedLength);

    if(tempstring)
    {
        *destination = tempstring;
        (*destination)[truncatedLength - 1] = '\0';
    }
    return tempstring;
} 

int main(void)
{
    char *a = malloc(10);
    strcpy(a, "123456789");
    dstring_truncate(&a, 5);
    printf("\"%s\"\n", a);
    free(a);
}

相关问题