[英]Segmentation fault (core dumped) allocating memory?
Im getting the error "Segmentation fault (core dumped)" when I run this program. 我在运行此程序时收到错误“Segmentation fault(core dumped)”。 I am new to c programming so its probably something stupid but i cant figure it out. 我是c编程的新手,所以它可能是愚蠢的东西,但我无法弄明白。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char *x, char *y){
char temp = *x;
*x=*y;
*y=temp;
}
char** getPermutations(char *string){
int length = strlen(string);
int startIndex = 0;
int endIndex = length - 1;
if(startIndex == endIndex){
printf("%s\n", string);
}else{
for(int j = startIndex; j<=endIndex; j++){
swap((string + startIndex),(string + j));
getPermutations(string);
swap((string+startIndex),(string+j));
}
}
}
int main(int argc, char *argv[]){
if(argc>2){
printf("\nToo Many arguments\n");
exit(0);
}else{
printf("%s",argv[1]);
char * str = malloc(strlen(argv[1]) + 1);
strcpy(str,argv[1]);
getPermutations(str);
}
}
Your issue is that getPermutations
calls itself endlessly. 您的问题是getPermutations
无休止地调用自己。 You need to pass something extra to it so it can know when to stop. 你需要传递额外的东西才能知道何时停止。 As is, it just calls itself over and over until you have a stack overflow. 就像它一样,它只是一遍又一遍地调用自己,直到你有一个堆栈溢出。
Also, you have getPermutations
setup to return a char**
, but then you never return anything. 此外,您已设置getPermutations
以返回char**
,但之后您永远不会返回任何内容。 So that's odd too. 所以这也很奇怪。
My suggestions: 我的建议:
Change the return type of the function to void
since it does not return anything. 将函数的返回类型更改为void
因为它不返回任何内容。
Change the name of the function to printPermutations
since it just prints the permutations. 将函数的名称更改为printPermutations
因为它只打印排列。
Provide a way to end the recursion. 提供一种结束递归的方法。 Pass startIndex
as an argument. 将startIndex
作为参数传递。
Pass the length of the string so you don't compute it every time the function is called recursively. 传递字符串的长度,这样每次递归调用函数时都不会计算它。
Change the comparison operator to >=
to account for zero length strings. 将比较运算符更改为>=
以考虑零长度字符串。
void printPermutations(char *string, int startIndex, int length){
int endIndex = length - 1;
if(startIndex >= endIndex){
printf("%s\n", string);
}else{
for(int j = startIndex; j<=endIndex; j++){
swap((string + startIndex),(string + j));
printPermutations(string, startIndex+1, length);
swap((string+startIndex),(string+j));
}
}
}
and call it with: 并称之为:
printPermutations(str, 0, strlen(str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.