-1

我正在尝试将字符串附加到文本文件中,但我得到了奇怪的字符。如果我尝试将结果打印到控制台,输出是正常的。这就是我在 vim 中看到的输出。如果我在 gedit 中查看它,我会得到奇怪的框。

输出文件:

  A^CA^BB^A
  A^CB^BA^A
  B^CA^BA^A

预期输出:

AAB
ABA
BAA

我的函数应该将没有重复的排列写出到文本文件中。

功能代码:

void RecursivePermute (char *prefix, char *rest, int *ptr)
{
    char *temp = malloc(sizeof(char *));
    char *new_prefix = malloc(sizeof(char *));
    char *rest_left = malloc(sizeof(char *));
    char *rest_right = malloc(sizeof(char *));
    char *new_rest = malloc(sizeof(char *));
    char rest_char;
    int idx = 0;
    int first_occurance = 0;
    int i;
    FILE *file;
    strcpy(temp, rest);
    if (*rest == '\0')
    {
        *ptr += 1;
        printf("Permutation %d: %s\n", *ptr, prefix);
        file = fopen("permutations.txt", "a");
        fprintf(file,"%s\n",prefix);
        fclose(file);
        return;
    }
    else
    {
        size_t rest_size = strlen(rest);
        while (*rest != '\0')
        {

            first_occurance = (strchr(temp, *rest) - temp - idx);
            if (first_occurance == 0)
            {
                rest_char = *rest;
                rest_left = strncpy(rest_left, rest-idx, idx);
                rest_right = strncpy(rest_right, rest+1, rest_size-1);
                sprintf(new_rest, "%s%s", rest_left, rest_right);
                sprintf(new_prefix,"%s%s", prefix, &rest_char);
                RecursivePermute( new_prefix, new_rest, ptr);
            }
            rest++;
            idx ++;
        }
    }
}
4

2 回答 2

0

一件事是您的 &rest_char 的 printf 格式说明符是错误的。&rest_char 不能解释为字符串,因为它不是以空值结尾的。如果要打印一个字符,请使用 %c。您的行应如下所示:

sprintf(new_prefix,"%s%c", prefix, rest_char);

Also you might want to look and see how you are allocating strings. By specifying a size of sizeof(char *) it will only create a memory allocation the size of a pointer. If the string in rest is greater than that it will cause a buffer overrun when you do the strcpy.

于 2012-11-18T04:07:23.730 回答
0

When you call malloc(sizeof(char *)), you are allocating a buffer of four bytes (or eight bytes if you are compiling for 64-bit). This almost certainly isn't what you want.

Then, you use strcpy() which doesn't check length. I almost never even use strcpy() anymore.

You also use strncpy(), which does check length, but I kind of hate it because it doesn't guarantee that the string will be properly null-terminated; if you copy a string that is length 4 or longer, and the buffer can hold only 4 characters, there is no null.

So, I haven't run your program under a debugger, but when you put all these problems together I am not suprised your program is misbehaving.

于 2012-11-18T04:09:40.013 回答