gpt4 book ai didi

C - 我的代码有什么问题(malloc、char*)

转载 作者:行者123 更新时间:2023-11-30 18:40:11 25 4
gpt4 key购买 nike

我只是想让你问我这段代码做错了什么。我写了一个函数,参数为 char*,我想直接修改它而不返回 smthg,并反转字符串。

#include <iostream>

void reverseString(char *p_string){

int length = strlen(p_string);
int r_it = length - 1;
char* tmp = (char*)malloc(length);
int last_it = 0;

for (int i = 0; i != length; i++){
tmp[i] = p_string[r_it];
r_it--;
last_it++;
}
tmp[last_it] = '\0';

strcpy_s(p_string, length + 1, tmp);
//free(tmp);
}

int main(){

char str[] = "StackOverflow";

reverseString(str);

std::cout << str << std::endl;

system("pause");
}

我习惯了C++,不经常使用C函数,如malloc/free/strcpy...在这里,我的问题是,当我为临时字符分配内存时,我为 length = 13 调用了 mallec(length),在本例中,char = 1 个字节,因此应该为 13 个字符分配内存,对吗?

问题是分配的空间比需要的多,所以我需要在 strcpy_s 之前使用“\0”,否则它会中断。

我是不是哪里做错了?另外,当我调用 free(tmp) 时,它也会崩溃并说堆损坏,但在此之前我没有释放内存。

感谢您的帮助!

最佳答案

我采用了您的原始代码,并在 malloc 的大小上添加了一个简单的“+1”,并得到了通过的结果。

不确定您的练习是否与 malloc 的使用特别相关,但您是否考虑过直接在原始字符串内进行反转?

例如:

void reverseString(char *p_string){

char* p_end = p_string+strlen(p_string)-1;
char t;

while (p_end > p_string)
{
t = *p_end;
*p_end-- = *p_string;
*p_string++ = t;
}
}

int main(){

char str[] = "StackOverflow";

reverseString(str);

std::cout << str << std::endl;

system("pause");
}

如果您需要使用malloc,那么您需要确保为包含'\0'的字符串分配足够的空间

关于C - 我的代码有什么问题(malloc、char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045854/

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