Home > OS >  Why is the structure causing a memory error?
Why is the structure causing a memory error?

Time:12-12

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

struct bank
{
    char *name [3]; 
    char *ha[3];
    int bal[3];
};

typedef   struct bank   bank;

int main()
{
    bank *SBI; 

    SBI=(bank*) malloc(sizeof(bank));

    strcpy(SBI->ha[0], "1234"); 

    printf("SUCCESS");

    return 0;
}

Why is the above code generating a memory write error? When I run the code it generates some error relating to memory. I am beginner in C programming. Can anyone help me about what is wrong in the code that is causing the error.

CodePudding user response:

You are copying your string into unallocated memory.

strcpy(SBI->ha[0], "1234")

Use strdup instead of strcpy. Strdup will allocate the memory for you.

CodePudding user response:

You also need to allocate space for your three strings ha[0], ha[1], ha[2]. Your malloc allocates memory for the bank structure, including three pointers, but these pointers need to be allocated too, with malloc or strdup for example:

for (int i = 0; i < 3; i  ) {
    bank->ha[i] = malloc(MY_STRING_MAXLENGTH);
}

which you later free:

for (int i = 0; i < 3; i  ) {
    free(bank->ha[i]);
}
free(SBI);
  • Related