我做節目有野牛在編輯一個PPM文件Ubuntu的給出,但我有一個分段故障核心轉儲的錯誤,我似乎無法修復它的用戶輸入,我的繼承人代碼:編輯文件時出現分段錯誤(核心轉儲)?
void ponto(int x, int y, char fname[100]){
int r,g,b;
int i,j;
int col,row;
int c = 255;
FILE *myFile = fopen(fname, "r");
if (myFile == NULL)
{
printf("Ficheiro nao existe");
}
else
fscanf(myFile, "P3\n%d%d\n255\n ", &col, &row);
fscanf(myFile,"%d %d %d\n ",&r,&g,&b);
FILE *fout = fopen(fname,"w");
fprintf(fout, "P3\n%d %d\n255\n",col,row);
for (j = 0;j < col;)
{
for (i = 0;i < row; i++)
{
if (j == y -1 && i == x - 1)
{
fprintf(fout,"0 0 0 ");
}
else
fprintf(fout,"%d %d %d ",r,g,b);
}
fprintf(fout,"\n");
j++;
}
fclose(fout);
}
和繼承人我的yacc代碼:
%{
#include <stdio.h>
#include "defs.h"
#include "funcoes.h"
Lista lista_variaveis = NULL; /* guarda o valor das variavaies definidas */
char * cfile = NULL; /* variavel currentfile para saber que ficheiro estamos a usar */
%}
%union {
int valor;
RES resolucao;
COR color;
COOR cord;
char * fname;
char * idvar;}
%type <resolucao> resol
%type <valor> num
%type <color> rgb
%type <valor> expr
%type <cord> coord
%token <idvar> IDVAR
%token <valor> INT
%token <fname> FNAME
%token SAIR NOVA ABRIR GUARDAR PONTO
%start s
%%
s : comando
;
comando : NOVA resol rgb ';'{makef($2.resx,$2.resy,$3.r,$3.g,$3.b);
cfile = "teste2.pnm";printf("%s",cfile); } comando
| ABRIR FNAME ';' {openf($2);cfile = $2}; comando
| PONTO coord ';' {ponto($2.xx,$2.yy,cfile);} comando
| GUARDAR
| defvar ';' comando
| SAIR {return 0; /*termina */ }
;
coord : expr ',' expr { $$.xx = $1; $$.yy = $3;}
;
resol : expr 'x' expr { $$.resx = $1; $$.resy = $3;}
;
rgb : expr':'expr':'expr { $$.r = $1; $$.g = $3; $$.b = $5;}
;
num : num '+' num { $$ = $1 + $3;}
| num '*' num { $$ = $1 * $3;}
| INT { $$ = $1;}
;
expr : num { $$ = $1;}
| IDVAR { $$ = valor_variavel(lista_variaveis, $1);}
;
defvar: IDVAR '=' num { define_variavel(&lista_variaveis,$1,$3);}
;
%%``
請使用調試器來遍歷代碼,告訴我們錯誤發生的位置。 –
我的猜測是該文件不存在程序正在查找的位置。你檢查NULL,但後面的'else'只適用於第一個'fscanf()'。第二個是無條件調用的,如果傳入一個NULL指針,你可以得到一個段錯誤。 – donjuedo
另外,您正在使用輸入和輸出相同的文件名,並且同時打開。至少,這不是好習慣。因爲我從來沒有嘗試過,所以我不能說出行爲是什麼,但是如果'fopen()'調用寫入結果失敗,並且返回NULL指針,我不會感到驚訝。該指針根本不被檢查,並傳入'fprintf'()'。如果爲NULL,那可能是崩潰的另一個來源。 – donjuedo