rubic
rubic

Reputation: 1

Failed to use fprintf() after a function is used

When I run parsertest, only one line "hello world" in the stdout, and nothing in add1.txt. But when I delete the line: char * nospace = delespace(line);, the stdout display many lines, which is the same as linenumber of add.txt, of "hello world", also the same lines "hello world" in add1.txt.

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

Upvotes: 0

Views: 36

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

In char * delespace(char * line) function,

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

The above malloc will allocate memory with the size of pointer + 1.

Hence when you access newline out of bound, you will get undefined behavior.

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

Try as below instead.

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

Upvotes: 1

Related Questions