-1

I'm running through a program and although the code is working fine, Valgrind is showing an 'Invalid write of Size 1' and Address 0x1ffefffa00 is on thread 1's stack.This has happened using both strchr and strchrn, another function in the program.

I've tried using index to locate the comma, as well as strchr and my strchr functions but all keep returning the same warning in Valgrind

typedef struct data_s Data;

struct data_s {
    float temperature;
    int year;
    int month;
    int day;

};

char* getData(FILE* filename) {
    char buffer[INPUT_LINE_MAX];
    char* dataLine = fgets(buffer, INPUT_LINE_MAX, filename);
    return dataLine;
}

Data* buildData(FILE* filename) {
    char* readLine = getData(filename);
    Data* new = malloc(sizeof(Data) + 1);
    char* comma1 = strchr(readLine, ',');

the rest of the code below comma1 is irrelevant

  • Possible duplicate of [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Sander De Dycker Aug 29 '19 at 07:23

1 Answers1

1

One problem will be that in the function getData() you are returning a pointer to a buffer that goes out of scope as soon as the function returns.

char buffer[INPUT_LINE_MAX]; is declared as a local variable and will be allocated on the stack. The memory for this will no longer be used when the function returns. Thus in you program, in the function buildData() the variable readLine points to a location on the stack that will probably be overwritten, at least in part, by the next function call(s)

Jimbo
  • 4,352
  • 3
  • 27
  • 44