Bus error in C structure

This is the code I'm testing to copy structure.

1 #include <stdio.h> 2 #include <string.h> 3 4 typedef struct emp_struct { 5 char *name; 6 int employee_no; 7 float salary, 8 tax_to_date; 9 } Employee; 10 11 typedef Employee Database[10]; 12 13 Database people = { 14 {"Fred", 10, 10000, 3000}, 15 {"Jim", 9, 12000, 3100.5}, 16 {"Fred", 13, 1000000, 30}, 17 {"Mary", 11, 170000, 4000}, 18 {"Judith", 45, 130000, 50000}, 19 {"Nigel", 10, 5000, 1200}, 20 {"Trevor", 10, 20000, 6000}, 21 {"Karen", 10, 120000, 34000}, 22 {"Marianne", 10, 50000, 12000}, 23 {"Mildred", 10, 100000, 30000} 24 }; 25 26 int main () { 27 // array act like pointer, thus pointing + pointing = ERROR 28 printf("people[1]->name: ERROR\n"); 29 // jump its memory amount of struct size 30 printf("(people+1)->name:%s\n",(people+1)->name); 31 // array works as a pointer 32 printf("people[3].name:%s\n",people[3].name); 33 34 /* Is it possible to assign struct to struct? */ 35 printf("\nAssigning struct to struct\n"); 36 Employee temp; 37 temp = *(people+5); // Nigel Record 38 printf("Name: %s\n",temp.name); 39 // exchange 40 strcpy(temp.name, "Ahn"); 41 printf("Changed: %s\n",temp.name); 42 printf("Original: %s\n",people[5].name); 43 44 return 0; 45 } 

When I tried to execute strcpy (new, string) on line 40, then it throws Bus Error: 10 .

I expected the value of Modified and Original to match on lines 41 and 42. But that will not work. What is the problem of assignment?

I knew that the bus error: 10 is due to a lack of destination space. But my name field in the structure is a pointer (on line 5). If I changed the name field, for example

  char name[100]; 

It works correctly and the Modified and Original value is different! Although I assigned this as a pointer.

What is the problem of assigning this structure?

+6
source share
2 answers

temp.name is a pointer to a char. After the copy temp = *(people+5); , temp.name points to bytes containing "Nigel".

Still no problem. But you cannot use this pointer as output for strcpy (); strcpy will try to overwrite it and store it in read-only memory.

You can do it:

temp.name = "Ahn";

... since all you do here is change the pointer (temp.name) to point to another area of โ€‹โ€‹memory that is pre-set to contain "Ahn".

This is actually not related to copying the structure. You will have the same problem if you try to do strcpy(people[3].name, "Ahn")

+3
source

When you declared a database record, all the names (Fred, Jim, Fred ...) were placed in the read-only memory of the data segment, and the name symbol pointer pointed to their starting addresses.

When you execute strcpy(temp.name, "Ahn"); , you are trying to write in read-only mode. Attempting to write read-only memory will result in a bus error.

The solution would be to allocate memory for name and then do strcpy . Also good programming practice is to use strncpy instead of strcpy

+1
source

All Articles