简体   繁体   English

需要帮助查找bug,如果字符串输入组成所有相同的字符,则一个输出字符已损坏

[英]Need help finding bug, if string input is composed all of same character one output character is corrupt

reverser() reverses a cstring (not in place). reverser()反转cstring(不到位)。 99% of the time it works but some input corrupts it for example it appears if aStr2[] is assigned a string made up of the same character it will have an error. 它工作的时间有99%,但有些输入会破坏它,例如,如果为aStr2 []分配了由相同字符组成的字符串,则会出现错误。

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

char* reverser(const char *str);

int main()
{
    char aStr[] = "aaa";
    char aStr2[] = "cccccc";
    printf("%s %s", aStr, aStr2);
    char* tmp = reverser(aStr2);//tmp now has garbage
    printf("\n%s", tmp);
    printf(" %s", aStr2);
    return 0;
}


char* reverser(const char *str)
{
    char* revStr = (char*)malloc(strlen(str));
    int i;
    for(i = strlen(str)-1; i >= 0; i--)
{
        revStr[strlen(str)-1-i] = str[i];
}
    return revStr;
}

Gives

aaa cccccc
cccccc9 cccccc
Process returned 0 (0x0)   execution time : 0.068 s
Press any key to continue

Notice the 9 that shouldn't be there. 注意不应该存在的9。

Your problem is that you don't put the string terminator in your reversed string. 您的问题是您没有将字符串终止符放在反向字符串中。 All strings in C are actually one extra character that isn't reported by strlen , and that is the character '\\0' (or plain and simple, a zero). C中的所有字符串实际上是strlen未报告的一个额外字符,即字符'\\0' (或简单和简单,零)。 This tells all C functions when the string ends. 这告诉字符串结束时所有C函数。

Therefore you need to allocate space for this extra terminator character in your malloc call, and add it after the last character in the string. 因此,您需要在malloc调用中为此额外的终结符字符分配空间,并将其添加到字符串中的最后一个字符之后。

There are also a couple of other problems with your code, the first is that you should not cast the return of malloc (or any other function returning void * ). 您的代码还有其他一些问题,第一个是您不应该转换malloc (或任何其他返回void *函数)的返回。 Another that you have a memory leak in that you do not free the memory you allocate. 另一个是你有内存泄漏,你没有释放你分配的内存。 This last point doesn't matter in a small program like the one you have here, but will be an issue in larger and longer running programs. 最后一点在像你这里的小程序中并不重要,但在更大和更长时间运行的程序中将是一个问题。

Change this malloc to strlen(str) + 1 , plus 1 for '\\0' 将此malloc更改为strlen(str)+ 1,将“0”更改为1

char* revStr = (char*)malloc(strlen(str) + 1);

and after the for loop 并在for循环之后

revStr[strlen(str)+1] = '\0';

You haven't null-terminated your reversed string. 您没有以null结尾反转字符串。 You need to set the final index of revStr[] to 0. 您需要将revStr []的最终索引设置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM