PacoProgramming
PacoProgramming

Reputation: 25

Issue with Memory Allocation using Struct Pointers

So, here is my issue, I've been stuck on this for a while now. This is working with linked lists... I have two structs declared as such

typedef struct BankAccountList *BankAccountListP;

struct BankAccountList {
   AccountNodeP head;
   int count;
};

AccountNodeP newNode(char *, int, double);

struct AccountNode {
   char *name;
   int id;
   double balance;
   AccountNodeP next;
};

Up until this pointer, this has worked just fine, when i try to allocate memory however...

AccountNodeP acctNodePtr = (AccountNodeP) malloc(sizeof(AccountNodeP));

Stops my program in its tracks. This is located in a function that returns the accountNodePtr.

The function:

AccountNodeP newNode(char *name, int id, double balance) {
   AccountNodeP acctNodePtr = (AccountNodeP) malloc(sizeof(AccountNodeP));
                        fprintf(stderr, "\nERROR 4\n");

   if (acctNodePtr == NULL) {
       fprintf(stderr, "\nERROR 10\n");         
   }
   acctNodePtr->next = NULL;
   acctNodePtr->id = id;
   acctNodePtr->balance = balance;
   strcpy(acctNodePtr->name, name);
   return acctNodePtr;
}

The first time and second time that this function is called it works but at the end my program still doesnt END correctly, it gets and error and stops running. However, the information is saved in the struct (I was able to tell using fprintf(stderr).) However, the third time I call it, it errors and stops my program at the AccountNodeP acctNodePtr = malloc... statement. I also know this because of using fprintf(stderr).

Can you see anything obviously wrong with my code? I'm not sure that I can pin point the issue. Please help me understand instead of just giving me the answer, I need to understand exactly what is happening.

NOTED: The error is in this function, my tester and adt file work fine other then this function. There is not a real need to give you the rest of my code because I'm sure the error is here somewhere.

Upvotes: 0

Views: 159

Answers (2)

barak manos
barak manos

Reputation: 30126

You are calling strcpy(acctNodePtr->name, name) without first initializing acctNodePtr->name to point to a valid memory address.

You can initialize it properly with acctNodePtr->name = malloc(strlen(name)+1).

Upvotes: 1

Eugene Sh.
Eugene Sh.

Reputation: 18299

If your AccountNodeP is a pointer to your structure, the sizeof(AccountNodeP) will return the size of the pointer and not of the structure. You might want to put sizeof(struct AccountNode) instead.

P.S. And DO NOT CAST the return of malloc!

Upvotes: 3

Related Questions