![](/img/trans.png)
[英]Redirecting program output in C, use fprintf or "more widely used" solution?
[英]Failed to use fprintf() after a function is used
當我運行parsertest時, stdout
只有一行“ hello world”,而add1.txt中沒有任何內容。 但是當我刪除該行時: char * nospace = delespace(line);
,標准輸出顯示多行,與“ hello world”的add.txt的行號相同,也與add1.txt中的“ hello world”的行相同。
-----------parsettest.c-----------------
#include "Parser.c"
#define MAXLEN 100
int main(void){
FILE * fp;
FILE * fp2;
if((fp = fopen("add.txt", "r")) == NULL){
printf("Can't open add.txt");
return 0;
}
if((fp2 = fopen("add1.txt", "w+"))== NULL){
printf("Can't creat add1.txt");
return 0;
}
char * line = (char *)malloc(sizeof(char) * MAXLEN);
while(fgets(line, MAXLEN, fp)){
printf("hello world\n" );
char * nospace = delespace(line);
fprintf(fp2, "hello world\n");
}
fclose(fp);
fclose(fp2);
return 0;
}
-------------Parser.c------------------------
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
char * delespace(char * line){
int i;
for(i = 0; line[i] == ' '; i++)
;
if(line[i] == '\n')
return NULL;
char * newline = malloc(sizeof(line) + 1);
int j = 0;
for(int i = 0; line[i] != '\0'; i++){
if(line[i] == ' ')
continue;
newline[j++] = line[i];
}
newline[j] = '\0';
printf("%s", newline);
return newline;
}
--------------add.txt----------------------------
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/06/add/Add.asm
// Computes R0 = 2 + 3 (R0 refers to RAM[0])
@2
D=A
@3
D=D+A
@0
M=D
在char * delespace(char * line)
函數中,
char * newline = malloc(sizeof(line) + 1);
上面的malloc
將以size of pointer
+ 1的size of pointer
分配內存。
因此,當您超出范圍訪問newline
時,將得到未定義的行為 。
newline[j++] = line[i];
請嘗試以下方法。
char * newline = malloc(strlen(line) + 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.