c语言分段错误

时间:2017-05-30 04:56:18

标签: c

这是代码。 我不知道如何解决这个问题。 这个程序是关于I / O文件并将每行格式转换为bin。 我得到了第一个,然后是分段错误的正确结果。 任何人都可以指出这是错的 谢谢

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


FILE *file, *newFile;

char output[13];

int main(int argc, char* argv[]){
    file = fopen(argv[1],"r");
    newFile = fopen("output.txt","wa+");
    char binary1[50];
    char first[2], secondDigit[2], third[2], last[2];
    char scr[5];
    char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101","0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110","1111"};
    char digits [] = "0123456789abcdef";

    while(fgets(scr, 5, file) && scr[5] != EOF) {
        char res[100];
        int p = 0;
        int value =0;
        while(scr[p])
        {
            const char * v = strchr(digits, tolower(scr[p]));

            if(v[0]>96){
                value=v[0]-87;
            }
            else{
                value=v[0]-48;
            }
            if (v){
                strcat(res, binary[value]);
            }
            p++;
        }
        printf("Res:%s\n", res);
    }       
    fclose(newFile);
    fclose(file);
    return 0;
}

2 个答案:

答案 0 :(得分:0)

问题是,当您到达行scr[p] \n时,char *strchr(const char *s, int c);的行为是NULL的行为,当它找不到时会返回c字符串s中出现v

分段错误是因为当您尝试取消引用时NULLv

您应该检查NULL何时file = fopen(argv[1],"r");并相应处理。

file执行NULL时,如果文件不存在,那么当您调用fgets(scr, 5, file)时,变量<div class="second"> <div class="col-md-12 text-center"> <form> <button class="btn btn-primary btn-lg" type="submit" formaction="1klasse.html">1.klasse </button> <button class="btn btn-primary btn-lg" type="submit" formaction="1klasse.html">2.klasse </button> </form> </div> </div> from sklearn.cluster import DBSCAN from sklearn.preprocessing import StandardScaler import numpy as np import matplotlib.pyplot as plt np.random.seed = 42 %matplotlib inline #Generate (x,y) data x = np.linspace(0.1,0.9,50) y = x%1 x += np.sin(2*x%1) y = y%0.2 #Shuffle (x,y) data ns = list(range(len(x))) np.random.shuffle(ns) x = x[ns] y = y[ns] """ Fit the Data """ X = [i for i in zip(x,y)] X = StandardScaler().fit_transform(X) """ Compute the DBSCAN """ db = DBSCAN(eps=0.5, min_samples=1).fit(X) labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) n_clusters_ """ Plot the clusters """ d= dict(zip(set(labels),['red','green','blue','yellow','purple','grey'])) d[-1] = "black" plt.scatter(x,y,color=[ d[i] for i in labels]) plt.show() 导致分段错误,这也是一个问题。

答案 1 :(得分:0)

发布的代码包含几个问题:

  • 不检查错误情况
  • 永远不会写入&#39; output.txt&#39;
  • 包含许多未使用的变量
  • 访问超出&#39; argv [0]&#39;没有先检查&#39; argc&#39;确保参数实际上是由用户输入的。
  • 不会从输入缓冲区的末尾删除可能的换行符序列
  • 如果遵循公理,
  • 会更具可读性:每行只有一个语句,并且(最多)每个语句一个变量声明。
  • 如果使用ascii char文字而不是数字,
  • 会更具可读性 如果代码块(for,if,else,while,while,while,switch,case default)通过一个空行分隔,那么
  • 将更具可读性。
  • 不检查“当前&#39;字符读取的范围是0 ... 9,而...是包含的
  • 不允许可能的&[39] res []&#39;缓冲区溢出。

现在提出的代码

#include <stdio.h>   // FILE, fopen(), fclose(), fgets(), fprintf(), fprint(), perror(), puts()
#include <string.h>  // strchr()
#include <stdlib.h>  // exit(), EXIT_FAILURE
#include <ctype.h>   // tolower()


#define MAX_INPUT_LEN  5


const char binary[][ MAX_INPUT_LEN ] =
{
    "0000",
    "0001",
    "0010",
    "0011",
    "0100",
    "0101",
    "0110",
    "0111",
    "1000",
    "1001",
    "1010",
    "1011",
    "1100",
    "1101",
    "1110",
    "1111"
};

const char digits [] = "0123456789abcdef";


int main(int argc, char* argv[])
{
    if( 2 != argc )
    {
        fprintf( stderr, "USAGE: %s inputFileName\n", argv[0] );
        exit( EXIT_FAILURE );
    }

    // implied else, correct number of arguments

    FILE *fpin = fopen(argv[1],"r");
    if( !fpin )
    {
        perror( "fopen for read of input file failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    //FILE *fpout = fopen("output.txt","wa+");
    //if( !fpout )
    //{
    //    perror( "fopen for output.txt for write failed" );
    //    fclose( fpin );   // cleanup
    //    exit( EXIT_FAILURE );
    //}

    // implied else, fopen successful

    //char binary1[50];
    //char first[2], secondDigit[2], third[2], last[2];

    // plus 2 to allow for possible newline and terminating NUL byte
    char scr[ MAX_INPUT_LEN+2 ];


    while( fgets(scr,  MAX_INPUT_LEN+2, fpin) )
    {
        // remove possible newline
        char *newline = strchr( scr, '\n' );
        if( newline )
        {
            *newline = '\0';
        }

        int value = 0;

        for( size_t i=0; scr[i]; i++ )
        {
            int temp = tolower(scr[i]);
            const char * v = strchr(digits, temp);
            if( !v )
            {
                printf( "non 'digit' in input line\n");
                continue;
            }

            if(v[0]>= 'a')
            {
                value= v[0] - 'a' + 10;  // result is 10...15
            }

            else
            {
                value= v[0] - '0'; // result is 0...9
            }

            printf( "%s", binary[value]);
        }
        puts("");
    }

    fclose( fpin );
    //fclose( fpout );
    return 0;
}