very bizzare file writing problem

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.

Is there something I have missed/misunderstood ?

many thanks

what exactly are you trying to do with the following ?
strcpy(str,file_name+1);

Change it to :
strcpy(str,file_name);

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.

The line strcpy(str,file_name+1); has problem

file_name+1 will make the pointer to move forward one char..

change it to strcpy(str,file_name);

Its quite long back I wrote a C program. So please correct me if am wrong.
Can we declare a array's size with a variable?

I meant will following line works ?
char sta[(int)strlen(data)];

yes ,it is possible to use variable as size of an array in C programming

Thanks for the info steephen

I experienced declaring array size as dynamic.
But wondering what is the difference with dynamic memory allocation?
rather than heap and stack.

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.

Regards

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.

Thanks fpmurphy. That helped solve my problems