c - 段错误,不知道原因

标签 c segmentation-fault stdio

我实际上尝试生成并填充随机矩阵并将其保存为纯文本、txt,但是当我尝试生成超过 1000 个文件而不相当于工作目录中的 2000 个文件时遇到问题。

我想了解其原因和解决方案。

我使用 gcc code.c 编译此代码并使用 ./a.out; 运行,可能会更改第 25 行中生成的矩阵数量:

cant = 1000; // THIS GENERATE 1000 FILES OF CURRENT MATRIX.

代码.c:

<小时/>

解决方案!!! =D

感谢 Chistopher 和 Vallabh

我认为对我来说,这个错误是线路上的疏忽

关闭(puntero_f); 关闭(puntero_b);

非常感谢您的解释,我想在对文件有更清晰的概念后我会得到它们。

最终理解为邮政编码,所以我把解决方案留给将来可能有用的人

非常感谢;)

<小时/>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

//  Usando Preprocesado para manejar las matrices y tener acceso eficiente a memoria
    #define F(i,j) F[i*col +j]  
    #define B(i,j) B[i*col +j]

float randfloat(float min, float max){    
    return ((float) rand() / (float) RAND_MAX);   
}

int i, j, tstep, fil, col, cant;

int main(int argc, char *argv[]){

    char nombre_b[50] ;     //= "";
    char nombre_f[50] ;     //= "";      
    FILE *puntero_f;
    FILE *puntero_b;

    fil = 2;
    col = 2;
    cant = 1000;

    int tam = fil*col;
    float *F = calloc(tam,sizeof(float));
    float *B = calloc(tam,sizeof(float));

    //srand((unsigned)time(NULL));

    int archi = 0;
    for (tstep=0; tstep<cant; tstep++){

        sprintf(nombre_f, "Forward%d.txt", tstep);
        sprintf(nombre_b, "Backward%d.txt", tstep);
        puntero_f = fopen(nombre_f, "a+");
        puntero_b = fopen(nombre_b, "a+");

        for(i = 0; i<fil; i++){
            for(j = 0; j<col; j++){
                F(i,j) = randfloat(0.0f, 1.0f);
                B(i,j)  = randfloat(0.0f, 1.0f);

                if(tstep==archi){
                    fprintf(puntero_f,"%f ", F(i,j));
                    fprintf(puntero_b,"%f ", B(i,j));
                }
            }
            if(tstep==archi){
                fprintf(puntero_f,"\n");
                fprintf(puntero_b,"\n");
            }
        }
        archi++;
        fclose(puntero_f);
        fclose(puntero_b);
    }

    return 0;
}

此时我就产生了一个问题,那就是生成的文件不是超过1000个吗?

txt只能生成Foward999.txt吗?文件?

最佳答案

问题是对 close 的调用()。如果您有fopen () 使用fclose ()。

open()/close() 使用整数文件描述符,

fopen()/fclose() 使用 FILE*。

代码中的问题是指针可以转换为整数,因此代码可以编译,但结果是崩溃!我用 fclose() 编译了你的代码,它工作得很好。

关于c - 段错误,不知道原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810103/

相关文章:

c - 尝试实现 Dijkstra,但存在毫无意义的段错误

在 C 编程中转换数组字符

c - atomic.h 中的操作似乎是非原子的

c++ - 我的 OpenCL 程序中的 SIGSEGV

android - 防止 WebView 中的 Flash Player 故障,就像 Android 浏览器所做的那样

c - 为什么调用 vprintf 或类似函数两次不起作用甚至出现段错误?

java - 为什么 System.err 在 Eclipse 中比 System.out 慢?

android - 在 C 和 Fmod : Functions gets undefined reference 中为 Android 编译终端 mp3player

c - fscanf - 如何处理两个 float +空格+换行符?

linux - fprintf 如何在 Linux 中阻塞?