使用函数后无法使用fprintf()

时间:2018-09-20 08:52:12

标签: c file-io printf

运行parsertest时,stdout中只有一行“ hello world”,而add1.txt中没有任何内容。 但是,当我删除行:char * nospace = delespace(line);时,stdout显示许多行,与“ hello world”的add.txt的行号相同,在add1.txt中也显示“ hello world”的行。 / p>

-----------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

1 个答案:

答案 0 :(得分:1)

char * delespace(char * line)函数中,

char * newline = malloc(sizeof(line) + 1);

以上malloc将用size of pointer + 1分配内存。

因此,当您越界访问newline时,您会得到未定义的行为

newline[j++] = line[i];

请尝试如下操作。

char * newline = malloc(strlen(line) + 1);