首页 文章

为什么我的程序在C中的字符串指针之间传输字符串时会崩溃?

提问于
浏览
0

我现在在c中遇到memcpy()的问题,希望有人可以提供帮助 .

我的程序允许用户将字符串输入到char指针中,然后计算所有可能的排列 . 当生成排列(用户输入指针变为排列)时,通过memcpy将排列复制到第二个char指针中 . 它完美地工作,除非字符串具有两个或更多不同的重复字符(例如“CCBB”或“AADD”) . 如果用户输入这样的内容,memcpy(甚至strcpy)会导致程序崩溃 .

void Permute(char * word, char ** printPerm, int start, int end)
{   
    if (start == end)
    {
        memcpy(printPerm[permIndex], word, strlen(word) + 1);
        ++permIndex;
    }
    else
    {
        for (int i = start; i <= end; ++i)
        {
            Swap((word + start), (word + i));
            Permute(word, printPerm, start + 1, end);
            Swap((word + start), (word + i));
        }
    }
}

void Swap(char *a, char *b)
{
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

我已经尝试为两个指针分配更多的内存,但事实证明它是徒劳的 . 除此之外,其他一切都有效 .

因为我在Windows上使用gcc(MinGW),所以我的崩溃细节没有显示出来 . 它只是说“perm.exe已停止工作” . 我使用了一系列printf()语句,发现程序在memcpy()行崩溃 .

关于代码的一些细节:

“word”字符指针保存用户的输入 . 它将被程序变成排列,它的内容将被转储到“printPerm”中 . “printPerm”是保存排列的char指针数组,稍后将用于在按字母顺序排序并删除任何重复条目时打印排列 . “permIndex”是“printPerm”的索引,并且每次将排列添加到“printPerm”时都会迭代 .

对不起,我没有更多细节,但使用文本编辑器和gcc意味着我没有太多的调试器 . 似乎任何在指针之间传递数据的方法都会使程序崩溃,如果字符串包含两个或多个不同的重复字符 .

1 回答

  • 0

    你很幸运:我的水晶球刚从维修中回来了!让我们看看它现在是否有效:

    // ALL CHECKS OMMITTED!
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    static int permIndex;
    
    // place the two functions you published here
    
    // Uhmmm...well...but we need one
    int factorial(int n)
    {
      int f = 1;
      do {
        f *= n;
      } while (--n);
    
      return f;
    }
    
    int main(int argc, char **argv)
    {
      int f,i;
      char **pperm;
      char *word;
      size_t length;
    
      if (argc < 2) {
        fprintf(stderr, "Usage: %s string\n", argv[0]);
        exit(EXIT_FAILURE);
      }
    
      // work on copy
      length = strlen(argv[1]);
      word = malloc(length + 1);
      strcpy(word, argv[1]);
    
      // You either allocate memory as you need it but as you compute
      // all combinations first, you need the whole memory for them
      // at once. That means the amount of memory needed is known in
      // advance and can be allocated at once
    
      f = factorial((int) length);
      // allocate memory for an array of (length)! pointers to char
      pperm = malloc(f * sizeof(char *));
      for (i = 0; i < f; i++) {
        // allocate memory for the n characters plus '\0'
        pperm[i] = malloc(length + 1);
      }
    
      Permute(word, pperm, 0, length - 1);
    
      // do something with the list
    
      // print it
      for (i = 0; i < f; i++) {
        printf("%s\n", pperm[i]);
        // we don't need the memory anymore: free it
        free(pperm[i]);
      }
      // free that array of pointers mjentioned above
      free(pperm);
      // free the memory for the input 
      free(word);
    
      exit(EXIT_SUCCESS);
    }
    

    这是实现这一目标的几种方法之一 .

相关问题