gpt4 book ai didi

c - 释放分配的字符串时内存损坏

转载 作者:行者123 更新时间:2023-11-30 16:51:53 24 4
gpt4 key购买 nike

当我尝试运行这个程序时,我收到错误 malloc(): 内存损坏。该错误并不是直接来自该函数,而是当我在此函数之后尝试 malloc() 时发生。如果我删除 free(ch) 行,它会正常工作,所以我猜当我尝试释放它时会发生损坏。main() 是我如何使用该函数的示例。

char * makeInt(int val){ 
char *res = malloc(5);
char l [5] = "";
sprintf(l,"%d",val);
if(val < 10){
strcat(res,"000");
strcat(res,l);
}
else if(val < 100){
strcat(res,"00");
strcat(res,l);
}
else if(val < 1000){
strcat(res,"0");
strcat(res,l);
}
else if( val < 10000){
strcat(res,l);
}
res[4] = '\0';
return res;
}


char * makeString(char *ch){
int t = strlen(ch);
char *chaine = malloc(t+4);
char *nb = makeInt(t);
strcat(chaine,nb);
strcat(chaine,ch);
chaine[t+4] = '\0';
free(ch);
return chaine;
}

int main(){
char *path = malloc(100);
// here we do many operations on path, when i call makeString, path contains something
path = makeString(path);
}

编辑:抱歉,我发帖时已经晚了,我忘记了一些信息。我添加了 makeInt().About include,我的代码中有它们,但我不认为错过的包含会导致内存损坏,因为它会编译。另外,当我调用 makeString() 时,路径包含一个字符串。我在代码中的不同位置使用 makeString() 。当我添加 free(ch) 错误时出现,但我不明白为什么释放在 main 中分配的内存会导致内存损坏。

最佳答案

发布的代码包含某些逻辑错误,例如:

strcat(chaine,nb);

但初始字符串必须有一个 NUL 字节,否则未知将返回什么值(即未定义的行为)

malloc() 返回的值的第一个字符中可能有也可能没有 NUL 字节。

这可能就是发布的代码导致段错误事件的原因。

(您可以使用 calloc() 而不是 malloc() 来解决此特定问题

此外,makeString() 的参数未初始化为任何特定的 NUL 终止字符串。因此,将该参数传递给 strlen()

是未定义的行为

(因为遇到的第一个 NUL 字节很可能超出“路径数组的末尾”)

一些建议:

  1. 阅读代码使用的任何系统函数的手册页。
  2. 单步执行任何代码(最好使用调试器)以查看其实际功能。

这里是一个可能适合您的代码版本。

#include <stdio.h>  // printf(), sprintf()
#include <stdlib.h> // malloc()
#include <string.h> // strlen(), strcat()

// prototypes
char * makeString(char *ch);


char * makeString(char *ch)
{
// EDIT: this line was wrong: char *chaine = malloc(sizeof(ch) + 7) // large enough to handle any int value
char *chaine = malloc(strlen(ch) + 7);

sprintf( chaine, "%4lu", strlen( ch ) );
strcat( chaine, " " );
strcat( chaine, ch );

return chaine; // the caller must call `free()`
} // end function: makeString


int main( void )
{
char *path = "my path string";
path = makeString(path);
printf( "%s\n", path );
free(path);
} // end function: main

输出是:

  14 my path string

关于c - 释放分配的字符串时内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528833/

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