c - Segmentation fault: 11 (caused by strncpy()) -


here code. struggling @ why strncpy() cant copy string struct, since works in previous assignment. also, have second question: suppose have struct contains struct, how assign value inside struct:

struct _field {     char fieldname[50];     char fieldtype[50];     int fieldlength; }; struct _table {     char *tablefilename;     int reclen;     int fieldcount;     struct _field fields[100];  };  typedef enum { false, true } bool;  bool loadschema(struct _table *table) {      printf("%s\n", "*** log: loading table fields...");      file *fp = null;     char lines[1000];     char s[2] = " ";      fp = fopen("in.txt", "r+");      while (fgets(lines, sizeof(lines), fp) != null) {         char *token;         token = strtok(lines, s);          if (token != null) {             if (strcmp(token, "createtable") == 0) {                 token = strtok(null, s);                 if (token != null) {                     token[strlen(token)-1] = '\0';                     strcat(token, ".bin");                     //table->tablefilename = token; // line can write value struct                     strncpy(table->tablefilename, token, 20);// line cant write value struct                 }                 printf("*** log: table name [%s]\n", table->tablefilename);             }             /*if (strcmp(token, "add") == 0) {                 token = strtok(null, s);                 if (token != null) {                        strncpy((*table).fields. fieldname, token, 50);                       }// q2: how give value struct of struct?             }*/         }     }     return 1; } 

input file looks this:

createtable people add id char 50 add lname char 50 

you getting segmentation fault because in code trying access pointer table no memory allocated points null. hence crash. solution problem copy these lines

table = (struct _table*)(malloc (sizeof(struct _table)));  table->tablefilename = (char *)(malloc (sizeof(char) * 20)); strncpy(table->tablefilename, token, 20); 

and remember free them. answer second question need assign value directly outer_struct.innerstruct.field1 = value outer_struct.innerstruct.field2 = value

or if inner structure pointer need initialize memory first , can either assign or directly use memcpy.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -