Note that there are some explanatory texts on larger screens.

plurals
  1. POMemory allocation and core dump for pointers to structures in c
    primarykey
    data
    text
    <p>Sorry I'm new to memory allocation and structure (so most probably it's some silly thing I've missed). I've got the following code which is core dumping on Solaris. I'm not also sure how to add more elements later (should I realloc memory?)</p> <pre><code> enum field_type { FLD_STRING, FLD_SHORT }; typedef struct { long id; char *name; field_type type; void *value; } myStruct_t ; typedef struct { long id; const char *name; field_type type; const char *descr; } myStructDef_t; myStructDef_t Alldef[] = { {0, "FirstField", FLD_STRING, "First Field Of Structure"}, {1, "SecondField", FLD_STRING, "Second Field Of Structure"}, {-1} }; int main() { myStruct_t *p_struct; char tmp[100] = {'\0'}; long id = 0; if(NULL == (p_struct= structAlloc(1024))) { print("Failed allocating memory\n"); return 0; } sprintf(tmp, "Test Adding value"); addValueToStruct(p_struct, id, (void *)tmp); } myStruct_t *structAlloc(long size) { myStruct_t *tmp = (myStruct_t *) calloc(size, sizeof *tmp); if(NULL != tmp) tmp-&gt;id = -1; return tmp; } int addValueToStruct(myStruct_t *p_struct, long id, (void *)value) { myStruct_t *bkStruct = p_struct; myStructDef_t *def = NULL; if(-1 == getIdDefinition(def, id)) { printf("Failed to find definition for id [%ld]", id); return -1; } // Core dumping on 1st line below bkStruct-&gt;id = def-&gt;id; sprintf(bkStruct-&gt;name, "%s", def-&gt;name); bkStruct-&gt;type = def-&gt;def-&gt;type; if(FLD_SHORT == bkStruct-&gt;type) memcpy(bkStruct-&gt;value, value, sizeof(*(short *)value)); else if(FLD_STRING == bkStruct-&gt;type) memcpy(bkStruct-&gt;value, value, sizeof(*(char *)value)); return 0; } int getIdDefinition(myStructDef_t *def, long id) { myStructDef_t *AllDefsTmp = Alldef; bool found = false; while( -1 != AllDefsTmp-&gt;id) { if(id == AllDefsTmp-&gt;id) { def = AllDefsTmp; found = true; break; } AllDefsTmp ++; } if(!found) return -1; return 0; } </code></pre> <p>Thanks :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload