I'm trying to write a function which opens a file pointer and writes one of the function parameters into the file, however for some reason Im getting a core dump error.
The code is as below
void WriteToFile(char *file_name, char *data)
{
FILE *fptr;
/*disk_name_size is a global variable*/
char str[disk_name_size + 5];
char sta[(int)strlen(data)];
strcpy(str,file_name+1);
strcat(str,".txt");
strcpy(sta,data);
/*Open file for appending*/
fptr = fopen(str,"a");
if(fptr != NULL)
{
fprintf(fptr,"%s",sta);
fclose(fptr);
}
}
I've ensured that the string length of the data passed into sta[] is no more than the num bytes assigned to it, plus all the parameters passed into WriteToFile() are not null.
However, irrgardless of this, it still crashes at fprintf() for some reason that continues to elude me.
The line char sta[(int)strlen(data) is problematic. When you call strcpy(sta,data) you overflow sta because of the trailing "\0" that strcpy() appends.
FWIK the use of a variable length array is only possible in C99 and some other languages, not in C.
The elements of an array must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution, array sizes are determined at the time of compilation.
For dynamic arrays, you would use malloc.
Local variables are always stack. If it was variable size, it would simply be dynamically choosing the amount of stack used. Which, like has been said, does not work with all compilers and C standards, so is best avoided.
By the way: strlen(str) is one smaller than the array size needed to store str, since a NULL terminator is also needed, so you want strlen(str)+1.