当我尝试检查空行时,出现分段错误?

问题描述:

因此,这里是到目前为止我的代码:当我尝试检查空行时,出现分段错误?

char *c; 
char inputString[200]; 

//get number of lines 
c=fgets(inputString, 200, in_file); 
while(c!=NULL){ 
    numLines++; 
    c=fgets(inputString, 200, in_file); 
} 

rewind(in_file); 

//array of instructions 
char** instruc = malloc(numLines * 200); 

c = fgets(inputString, 200, in_file); 

//fill the array of instructions. 
while (c != NULL){ 
    //allocate space for the string in the index of the array 
    instruc[i] = malloc(200); 
    strcpy(instruc[i], inputString); 
    if (strcmp(instruc[i], "\n")==0){ 
     fprintf(stderr, "Blank line.\n"); 
     exit(-2); 
    } 
    i++; 
    c = fgets(inputString, 200, in_file); 
} 

出于某种原因,我的strcmp(instruc [I],“/ N”)没有赶上在我的脚本中的新行,所以每当我的代码遇到新行,我得到一个分段错误。下面是一个示例脚本我通过:

CONST R1 11 

PUSH R1 
CONST R2 12 

CONST R1 11和PUSH R1之间,我得到一个分段错误。任何人都可以帮助我如何检查行之间的空白?谢谢!

您的程序的空(空白)行为"\n"而不是"/n"

+0

哦!谢谢,去了,并修复了...但是,我仍然得到一个段错误... – user2253332 2013-04-25 04:13:29

您的代码中存在其他问题。

char** instruc = malloc(numLines * 200); 

这不会给你一个动态的二维字符数组,如你所想象的那样。

下面是创建动态字符串数组..

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

#define ROW_SZ 5  //row size is number of strings 
#define COL_SZ 200  //column size is number of characters in a string 

int main() 
{ 
int i; 
char** str = malloc(ROW_SZ * sizeof(char*));  //str is assigned char** 

for (i = 0; i < ROW_SZ; i++) 
    str[i] = malloc(COL_SZ * sizeof(char)); //str[i] is assigned char* 

// code here to use your dynamic 2-d string 


for (i = 0; i < ROW_SZ; i++) 
    free(str[i]); 

free(str); 

return 0; 
} 

空白线被用 “\ n” 个不与 “/ n” 个相比SSCCE

+0

我修正了这一点,但我仍然得到段错误。 – user2253332 2013-04-25 19:36:43

+0

没有收到任何段错误,对我来说工作正常。你可以使用gdb进行调试吗?这样就可以很容易地跟踪它在哪里被触发。 – 2013-04-26 03:18:39

逻辑错误在这片代码

if (strcmp(instruc[i], "/n")==0){ 
     fprintf(stderr, "Blank line.\n"); 
     exit(-2); 
    } 

在这里,您正在使用“/ N”而不是“\ n”检查空行。

+0

我修正了这个问题,但我仍然遇到段错误。 – user2253332 2013-04-25 19:37:14

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

int main(void){ 
    char inputString[200]; 
    size_t i, numLines = 0; 
    FILE *in_file = fopen("input.txt","r"); 

    while(NULL!=fgets(inputString, sizeof(inputString), in_file)){ 
     if (strcmp(inputString, "\n")==0){ 
      fprintf(stderr, "Blank line.\n"); 
      exit(-2); 
     } 
     ++numLines; 
    } 

    rewind(in_file); 

    char** instruc = malloc(numLines * sizeof(char*)); 

    for(i=0;i<numLines;++i){ 
     instruc[i] = malloc(sizeof(inputString)); 
     fgets(instruc[i], sizeof(inputString), in_file); 
    } 
    fclose(in_file); 
    //do something 
    //deallocate memory 
    return 0; 
}