1

C - Segmentation fault when closing a file

 2 years ago
source link: https://www.codesd.com/item/c-segmentation-fault-when-closing-a-file.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C - Segmentation fault when closing a file

advertisements

I've come across a weird issue where I receive a segmentation fault when trying to close the file. Data is being written to the file correctly, could there be some sort of race condition happening between fflush and fclose?

//main.c

#define filename "/home/test.txt";
char fbuf[255];
sprintf(fbuf, "%s, %f, %f,%f \n", "big", 8.0,0.0,0.8);

sendFile(&fbuf, sizeof(fbuf), (void *)filename);

static void
sendFile( void *data, int size, char *pName)
{
    FILE *pFile = fopen(pName,"a");
    char *buf = NULL;
    buf = (char *)malloc(255);
    memcpy(buf, data, sizeof(char *)*size);

    if(pFile == NULL) {
        logger(LOG_INFO, "Error opening file\n");
}
    else {
        fwrite(buf, 1, strlen(buf), pFile);
        fflush(pFile);
        fclose(pFile);
    }
    free (buf);
}

Any help or suggestions are greatly appreciated.


I think the problem is in memcpy(buf, data, sizeof(char *)*size).

Shouldn't it be simply memcpy(buf, data, size)?

Looking at your example, fbuf (i.e. data) is 255 chars, and buf is 255 chars as well. But the memcpy is copying more than one thousand chars effectively writing garbage into the heap, with unpredictable results.

Tags fclose

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK