-1

I've been struggling with fread. Even though I'm adding the end of string character '\0', sometimes there is a random character at the end of the string.

Here is my code.

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

uint8_t get_acks(char ** acks);

int main(){
    ...
    char *acks = NULL;
    uint8_t r = get_acks(&acks);
    // test r ...
}


uint8_t get_acks(char ** acks){

    FILE *fp;
    fp = fopen(FILENAME, "r");
    // test fp

    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    *acks = malloc(sizeof(char)*(len+1));

    fread(*acks, sizeof(char), len, fp);

    acks[len-1] = '\0';

    printf("acks in get_acks: %s", *acks);

    return 0;
}

I've also tried *acks[len-1] = '\0' but the program crashes (nothing is printed from that point on)

Here you have an output example:

acks in get_acks: 1, 2, 3, 4 09:09▒

Here is the file content:

cat new_acks.txt: 1, 2, 3, 4

lmbcerqueira
  • 187
  • 1
  • 1
  • 14

1 Answers1

3

acks is double pointer holding address of acks from main

You need to change

acks[len - 1] = '\0';

to

(*acks)[len] = '\0';

So that buffer you allocated in get_acks gets \0 at the end

JeremyP
  • 84,577
  • 15
  • 123
  • 161
Pras
  • 4,047
  • 10
  • 20