Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 斐波那契动态内存管理_C_Memory_Fibonacci - Fatal编程技术网

C 斐波那契动态内存管理

C 斐波那契动态内存管理,c,memory,fibonacci,C,Memory,Fibonacci,我目前正在为一个项目开发斐波那契,在管理内存时遇到了一些问题。在实现过程中,我使用for和recursive by rfib函数执行一个迭代结构。虽然打印过程正常,但似乎内存有问题。 修改后显示的错误为:异常1(进程8076)正常退出 void rfib(int *fib, int x, int last); int main (int argc, char *argv[]) { int N,x; int *s = NULL; char *str, *str2;

我目前正在为一个项目开发斐波那契,在管理内存时遇到了一些问题。在实现过程中,我使用for和recursive by rfib函数执行一个迭代结构。虽然打印过程正常,但似乎内存有问题。 修改后显示的错误为:异常1(进程8076)正常退出

void rfib(int *fib, int x, int last);
int main (int argc, char *argv[]) {
    int N,x;
    int *s = NULL; 
    char *str, *str2;

    if(argv[1] == NULL) {
        exit(1);
    }

    N = atoi(argv[1]);

    s = malloc(sizeof(int)*N);
    str = malloc(sizeof(char)*N);
    str2 = malloc(sizeof(char)*N);  

    if (s==NULL) {
        exit(1);
    }

    s[0]=0;
    s[1]=1;

    // Calculate Fibonacci Serie.
    for (x=2;x<N;x++) { 
        s[x] = s[x-2] + s[x-1];  
    }
    // Print Fibonacci Serie.
    str2 = "Iterative Fibonacci Calculation";
    for (x=0;x<N;x++) {
        sprintf(str,"%s %d: %d\n",str2, x, s[x]);
        write(1,str,strlen(str));
    }

    rfib(s,0,N);

    //Print Fibonacci Serie.
    str2 = "Recursive Fibonacci calculation";
    for (x=0;x<N;x++) {
        sprintf(str,"%s %d: %d\n", str2, x, s[x]);  
        write(1,str,strlen(str));
    }

    str2 = NULL;
    str = NULL;
    s = NULL;
    free(str2);
    free(str);
    free(s);    
    exit(0);
}


void rfib(int *fib, int x, int last) {
    if (x == 0) {
        fib[0] = 0;
    } else if (x == 1) {
        fib[1] = 1;
    } else if (x > 1) {
        fib[x] = fib[x-1] + fib[x-2];
    }

    if (x != last) {
        rfib(fib,x + 1,last);
    }
}
void rfib(int*fib,int x,int last);
int main(int argc,char*argv[]){
int N,x;
int*s=NULL;
字符*str,*str2;
如果(argv[1]==NULL){
出口(1);
}
N=atoi(argv[1]);
s=malloc(sizeof(int)*N);
str=malloc(sizeof(char)*N);
str2=malloc(sizeof(char)*N);
如果(s==NULL){
出口(1);
}
s[0]=0;
s[1]=1;
//计算斐波那契级数。

对于(x=2;xYou
s=malloc(sizeof(int)*N);
已经为
N
int分配了空间…但是,在一个循环中,您尝试
s=(int*)realloc(s,(x+1)*sizeof(int));
将其更改为3、4、…、N intsAn数组(或malloc的d内存)的空间使用
N
元素具有从
0
N-1
的有效索引。您尝试在递归函数中访问
array[N]
。感谢您的评论,我做了一些更改,但出现了一个错误:次1(进程8076)正常退出,但“次1(进程8076)正常退出”(我强调)这不是一条错误消息,而是一条成功消息。您的问题到底是什么?请回答您的问题以显示更改。请通过添加新源来执行此操作,以便我们也可以看到旧源。