I am trying to read a file line by line, and get each line as a char * to a dynamic string, the code I am using used to work and without changing it (or noticing it), it has ceased to work, accsesing the reed information results in an error. Here is a MRE of my code for getting one line:
#include <stdio.h>
#include <string.h>
#define MAX_STR_SIZE 10000
int main(void)
{
char* filePath; // is set by other working part of program to a real readable file address.
while (fgetc(filePath) != EOF) // an extra chracter is in the data files to account for this cheack.
{
char tempStr[MAX_STR_SIZE] = { 0 };
char* str = NULL;
fgets(tempStr, MAX_STR_SIZE, filePath);
tempStr[strcspn(tempStr, "\n")] = 0;
str = malloc(sizeof(char) * (strlen(tempStr) + 1)); // does not work
strcpy(str, tempStr);
}
}
The error: Exception thrown at 0x00007ff95448d215 in GifProject.exe: Access violation writing location 0xFFFFFFFFEA1854F0.
It is difficult to diagnose your problem without a complete compilable program that exhibits the problem, but from the code fragment and the debugging information in the image, it seems you do not include
<stdlib.h>and the prototype inferred by the compiler formalloc()from the actual argument isint malloc(size_t), leading to undefined behavior when you store the return value into the pointerstr: because of the missing prototype, the compiler generates code that converts the return value frominttochar *, sign extending from 32-bit to 64-bits, producing a meaningless pointer.Note that you should also test the return value of
fgetsto properly handle end of file, and you should test for potentialmallocfailure before callingstrcpyor better: usestrdupthat allocates and copies a string in a single call.Here is a modified version: