c - 堆损坏问题 - C

标签 c malloc

我正在制作一个“简单”的打印字符串,追加字符串并从字符串中删除部分。 append 和 new string 有时会起作用,有时它什么都不输出。 当我这样做时:

char * temp = malloc(newSize);

它只是停止输出任何东西。

我已经分段注释掉所有内容,试图找出问题所在。似乎找不到问题,但谷歌不断提出“堆损坏”。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char * data;
    int length;
} String;

int str_getLength(const char * characters)
{
    int index = 0;
    while (1)
    {
        if (characters[index] == '\0') break;
        index++;
    }
    return index;
}

String str_new(const char * characters) 
{
    String result;
    result.length = str_getLength(characters);
    result.data = malloc(result.length);
    memcpy(result.data, characters, result.length);
    return result;
}

void str_append(String * str, const char * characters) 
{
    int charsLength = str_getLength(characters);
    str->data = realloc(str->data, charsLength);
    for (int i = 0; i < charsLength; i++) {
        str->data[i + str->length] = characters[i];
    }
    str->length = str->length + charsLength;
}

void str_remove(String * str, int startIndex, int endIndex) 
{
    if (startIndex < 0 || endIndex > str->length || endIndex < startIndex) {
        return;
    }
    int chunkSize = endIndex - startIndex;
    int newSize = str->length - chunkSize;

    char * temp = malloc(newSize);
    // for (int i = 0; i < str->length; i++) 
    // {
    //  if (i < startIndex || i > endIndex) {
    //      temp[i] = str->data[i];
    //  } 
    // }

    // free(str->data);
    // str->length = newSize;
    // str->data = temp;
}
}

int main() 
{
    String str = str_new("Hello, ");
    printf("%s\n", str.data);

    str_append(&str, "this is my first C application.");
    printf("%s\n", str.data);

    str_remove(&str, 0, 3);
    printf("%s\n", str.data);

    free(str.data);

    return 0;
}

我原以为它会输出一个修改后的字符串,但它没有,有时它什么也不输出。 我是初学者,抱歉,如果这是一个快速修复。

最佳答案

除了大火的答案。 还有一些问题。

// for (int i = 0; i < str->length; i++) 
// {
//  if (i < startIndex || i > endIndex) {
//      temp[i] = str->data[i];
//  } 
// }

您将越界访问 temp。 您需要为 temp 维护单独的索引。

char * temp = malloc(newSize+1);
int k=0;
for (int i = 0; i < str->length; i++) 
 {
  if (i < startIndex || i > endIndex) {
      temp[k++] = str->data[i];
  } 
}
 temp[k] = '\0'; 
 free(str->data);
 str->length = newSize;
 str->data = temp;

您不是 null 在附加后终止字符串。

str->data = realloc(str->data, str->length + charsLength +1); //current length + new length + \0
for (int i = 0; i < charsLength; i++) {
    str->data[i + str->length] = characters[i];
}
 str->data[i + str->length] = '\0'; //null terminate the new string
str->length = str->length + charsLength;

关于c - 堆损坏问题 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664354/

相关文章:

c - 列表C中字符串的动态内存分配

用Notepad++编译生命游戏(C)

c++ - C++中 vector 的Malloc错误

c++ - 使用 C 扫描 wifi 网络

c - C 中的 getopts,命令行参数

c - 内存分配阈值(mmap 与 malloc)

使用第二个参数作为目录复制文件

c - 以下带有 malloc 的代码行是做什么的?

c++ - 使用 malloc() 时如何实现复制构造函数

c - 为什么我的 MPI 程序没有按预期打印