Tarek M. Mousa
Tarek M. Mousa

Reputation: 1

How to fix "Access violation writing location 0xFFFFFFCD."?

I want to read data from a FILE and save it to a linked-list and my problem is apparently with the reading command "fscanf".

I'm trying to make a function that receives a head of a linked-list and a pointer to a file. The function reads the data from the file and saves them into a node then connects the node to the beginning of the linked list, i.e. to the head, not to the end.

#include <stdio.h>
#include <stdlib.h>

#define NameLength 15

typedef struct Product {
    char ProductName[NameLength];
    int Quantity;
    int Price;
    char Premium;
}Product;

typedef struct ProductList {
    Product P;
    struct ProductList* next;
}ProductList;

void DeleteList(ProductList*);
void ErrorMsg(const char*);
int CheckInList(ProductList*, const char*);

void CreateProducts(ProductList *head, FILE *fp) {
    ProductList *temp = (ProductList*)malloc(sizeof(ProductList));
    //If the dynamic memory allocation for temp has failed, print a 
message and exit the program.
    if (!temp) {
        DeleteList(head);
        ErrorMsg("Error: Memory allocation of temp in CreateProducts has 
failed.");
     }

    temp->next = NULL;
    while (!feof(fp)) {
        fscanf(fp, "%s%d%d%c", temp->P.ProductName, &temp->P.Quantity, 
&temp->P.Price, temp->P.Premium);
        if (CheckInList(head, temp->P.ProductName))
            printf("Error: Product is already found in the list.\n");
        else {
            if (temp->P.Quantity < 0)
            printf("Error: Quantity of the product cannot be 
negative.\n");
            else {
                if (temp->P.Price < 0)
                    printf("Error: Price of the product cannot be 
negative.\n");
                else
                {
                    //Adding the product to the beginning of the list 
every time.
                    if (head == NULL)
                        head = temp;
                    else
                    {
                        temp->next = head->next;
                        head->next = temp;
                    }
                }
            }
        }
    }
    if (head != NULL)
        printf("Products' information have been received.\n");
    else
        ErrorMsg("Products' information have NOT been received.");
}

Upvotes: 0

Views: 273

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

Turn on your compiler's warnings! It will literally give you the answer.

main.cpp: In function 'void CreateProducts(ProductList*, FILE*)':
main.cpp:33:20: warning: format '%c' expects argument of type 'char*', but argument 6 has type 'int' [-Wformat=]
         fscanf(fp, "%s%d%d%c", temp->P.ProductName, &temp->P.Quantity,
                    ^~~~~~~~~~
 &temp->P.Price, temp->P.Premium);
                 ~~~~~~~~~~~~~~~

(I know it says main.cpp; that's just an artefact of the online compiler, which I put into C mode.)

Upvotes: 5

Related Questions