Pointer seg faulting although I malloc-ed right Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!What are the differences between a pointer variable and a reference variable in C++?What is a smart pointer and when should I use one?Do I cast the result of malloc?What REALLY happens when you don't free after malloc?How do function pointers in C work?Difference between malloc and calloc?What is a segmentation fault?valgrind reports malloc assertion failure, memcheck doesn't report any errorsc malloc error code :3096Why should I use a pointer rather than the object itself?

Is the Standard Deduction better than Itemized when both are the same amount?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

Should I use a zero-interest credit card for a large one-time purchase?

Why do people hide their license plates in the EU?

What would be the ideal power source for a cybernetic eye?

51k Euros annually for a family of 4 in Berlin: Is it enough?

Using et al. for a last / senior author rather than for a first author

When do you get frequent flier miles - when you buy, or when you fly?

How to run gsettings for another user Ubuntu 18.04.2 LTS

How to Merge Multiple Columns in to Two Columns based on Column 1 Value?

Bete Noir -- no dairy

Single word antonym of "flightless"

What to do with chalk when deepwater soloing?

How can I make names more distinctive without making them longer?

Why didn't this character "real die" when they blew their stack out in Altered Carbon?

Identify plant with long narrow paired leaves and reddish stems

List *all* the tuples!

How to tell that you are a giant?

What does the "x" in "x86" represent?

Why is my conclusion inconsistent with the van't Hoff equation?

Can I cast Passwall to drop an enemy into a 20-foot pit?

How to find all the available tools in mac terminal?

Should I discuss the type of campaign with my players?

What exactly is a "Meth" in Altered Carbon?



Pointer seg faulting although I malloc-ed right



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!What are the differences between a pointer variable and a reference variable in C++?What is a smart pointer and when should I use one?Do I cast the result of malloc?What REALLY happens when you don't free after malloc?How do function pointers in C work?Difference between malloc and calloc?What is a segmentation fault?valgrind reports malloc assertion failure, memcheck doesn't report any errorsc malloc error code :3096Why should I use a pointer rather than the object itself?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















I don't understand why my program seg faults at this line: if ((**table->table).link == NULL){ I seem to have malloc-ed memory for it, and I tried looking at it with gdb. *table->table was accessible and not NULL, but **table->table was not accessible.
Definition of hash_t:



struct table_s 
struct node_s **table;
size_t bins;
size_t size;
;

typedef struct table_s *hash_t;

void set(hash_t table, char *key, int value)
unsigned int hashnum = hash(key)%table->bins;
printf("%d n", hashnum);
unsigned int i;
for (i = 0; i<hashnum; i++)
(table->table)++;

if (*(table->table) == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
*(table->table) = malloc(sizeof(struct node_s));
*(table->table) = np;
else
while ( *(table->table) != NULL)
if ((**table->table).link == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
(**table->table).link = malloc(sizeof(struct node_s));
(**table->table).link = np;
break;
else if (strcmp((**table->table).key, key) == 0)
break;

*table->table = (**(table->table)).link;

if (table->size/table->bins > 1)
rehash(table);





I'm calling set from here:



 for (int i = 0; i < trials; i++) 
int sample = rand() % max_num;
sprintf(key, "%d", sample);
set(table, key, sample);










share|improve this question



















  • 3





    That's a lot of dereferencing. Why don't you show us the definition of hash_t?

    – M Oehm
    Mar 8 at 17:40






  • 2





    Please create a Minimal, Complete, and Verifiable example

    – machine_1
    Mar 8 at 17:41











  • You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

    – Jabberwocky
    Mar 8 at 17:41











  • When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

    – hyde
    Mar 8 at 17:42






  • 2





    Use a debugger: Step through your code and examine variables

    – abelenky
    Mar 8 at 17:51

















-1















I don't understand why my program seg faults at this line: if ((**table->table).link == NULL){ I seem to have malloc-ed memory for it, and I tried looking at it with gdb. *table->table was accessible and not NULL, but **table->table was not accessible.
Definition of hash_t:



struct table_s 
struct node_s **table;
size_t bins;
size_t size;
;

typedef struct table_s *hash_t;

void set(hash_t table, char *key, int value)
unsigned int hashnum = hash(key)%table->bins;
printf("%d n", hashnum);
unsigned int i;
for (i = 0; i<hashnum; i++)
(table->table)++;

if (*(table->table) == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
*(table->table) = malloc(sizeof(struct node_s));
*(table->table) = np;
else
while ( *(table->table) != NULL)
if ((**table->table).link == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
(**table->table).link = malloc(sizeof(struct node_s));
(**table->table).link = np;
break;
else if (strcmp((**table->table).key, key) == 0)
break;

*table->table = (**(table->table)).link;

if (table->size/table->bins > 1)
rehash(table);





I'm calling set from here:



 for (int i = 0; i < trials; i++) 
int sample = rand() % max_num;
sprintf(key, "%d", sample);
set(table, key, sample);










share|improve this question



















  • 3





    That's a lot of dereferencing. Why don't you show us the definition of hash_t?

    – M Oehm
    Mar 8 at 17:40






  • 2





    Please create a Minimal, Complete, and Verifiable example

    – machine_1
    Mar 8 at 17:41











  • You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

    – Jabberwocky
    Mar 8 at 17:41











  • When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

    – hyde
    Mar 8 at 17:42






  • 2





    Use a debugger: Step through your code and examine variables

    – abelenky
    Mar 8 at 17:51













-1












-1








-1








I don't understand why my program seg faults at this line: if ((**table->table).link == NULL){ I seem to have malloc-ed memory for it, and I tried looking at it with gdb. *table->table was accessible and not NULL, but **table->table was not accessible.
Definition of hash_t:



struct table_s 
struct node_s **table;
size_t bins;
size_t size;
;

typedef struct table_s *hash_t;

void set(hash_t table, char *key, int value)
unsigned int hashnum = hash(key)%table->bins;
printf("%d n", hashnum);
unsigned int i;
for (i = 0; i<hashnum; i++)
(table->table)++;

if (*(table->table) == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
*(table->table) = malloc(sizeof(struct node_s));
*(table->table) = np;
else
while ( *(table->table) != NULL)
if ((**table->table).link == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
(**table->table).link = malloc(sizeof(struct node_s));
(**table->table).link = np;
break;
else if (strcmp((**table->table).key, key) == 0)
break;

*table->table = (**(table->table)).link;

if (table->size/table->bins > 1)
rehash(table);





I'm calling set from here:



 for (int i = 0; i < trials; i++) 
int sample = rand() % max_num;
sprintf(key, "%d", sample);
set(table, key, sample);










share|improve this question
















I don't understand why my program seg faults at this line: if ((**table->table).link == NULL){ I seem to have malloc-ed memory for it, and I tried looking at it with gdb. *table->table was accessible and not NULL, but **table->table was not accessible.
Definition of hash_t:



struct table_s 
struct node_s **table;
size_t bins;
size_t size;
;

typedef struct table_s *hash_t;

void set(hash_t table, char *key, int value)
unsigned int hashnum = hash(key)%table->bins;
printf("%d n", hashnum);
unsigned int i;
for (i = 0; i<hashnum; i++)
(table->table)++;

if (*(table->table) == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
*(table->table) = malloc(sizeof(struct node_s));
*(table->table) = np;
else
while ( *(table->table) != NULL)
if ((**table->table).link == NULL)
struct node_s n = key, value, NULL;
struct node_s *np = &n;
(**table->table).link = malloc(sizeof(struct node_s));
(**table->table).link = np;
break;
else if (strcmp((**table->table).key, key) == 0)
break;

*table->table = (**(table->table)).link;

if (table->size/table->bins > 1)
rehash(table);





I'm calling set from here:



 for (int i = 0; i < trials; i++) 
int sample = rand() % max_num;
sprintf(key, "%d", sample);
set(table, key, sample);







c pointers hash segmentation-fault malloc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 18:01









melpomene

62.7k55195




62.7k55195










asked Mar 8 at 17:38









Prionti NasirPrionti Nasir

84




84







  • 3





    That's a lot of dereferencing. Why don't you show us the definition of hash_t?

    – M Oehm
    Mar 8 at 17:40






  • 2





    Please create a Minimal, Complete, and Verifiable example

    – machine_1
    Mar 8 at 17:41











  • You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

    – Jabberwocky
    Mar 8 at 17:41











  • When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

    – hyde
    Mar 8 at 17:42






  • 2





    Use a debugger: Step through your code and examine variables

    – abelenky
    Mar 8 at 17:51












  • 3





    That's a lot of dereferencing. Why don't you show us the definition of hash_t?

    – M Oehm
    Mar 8 at 17:40






  • 2





    Please create a Minimal, Complete, and Verifiable example

    – machine_1
    Mar 8 at 17:41











  • You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

    – Jabberwocky
    Mar 8 at 17:41











  • When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

    – hyde
    Mar 8 at 17:42






  • 2





    Use a debugger: Step through your code and examine variables

    – abelenky
    Mar 8 at 17:51







3




3





That's a lot of dereferencing. Why don't you show us the definition of hash_t?

– M Oehm
Mar 8 at 17:40





That's a lot of dereferencing. Why don't you show us the definition of hash_t?

– M Oehm
Mar 8 at 17:40




2




2





Please create a Minimal, Complete, and Verifiable example

– machine_1
Mar 8 at 17:41





Please create a Minimal, Complete, and Verifiable example

– machine_1
Mar 8 at 17:41













You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

– Jabberwocky
Mar 8 at 17:41





You should also show us how you call set, the origin of the problem might be in the calling code. Please read this: How to Ask and this: Minimal, Complete, and Verifiable example

– Jabberwocky
Mar 8 at 17:41













When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

– hyde
Mar 8 at 17:42





When you have that complex dereferencing experssion, and you have a bug in your code, open it up. Create temp variables, and do one referencing at a time. If you don't see your problem while writing that code, then run it under debugger and it's usually easy to figure out where exactly you dereference an invalid pointer.

– hyde
Mar 8 at 17:42




2




2





Use a debugger: Step through your code and examine variables

– abelenky
Mar 8 at 17:51





Use a debugger: Step through your code and examine variables

– abelenky
Mar 8 at 17:51












1 Answer
1






active

oldest

votes


















0














Your hashtable works like this: You have bins bins and each bin is a linked list of key / value pairs. All items in a bin share the same hash code modulo the number of bins.



You have probably created the table of bins when you created or initialised the hash table, something like this:



table->table = malloc(table->bins * sizeof(*table->table);

for (size_t i = 0; i < table->bins; i++) table->table[i] = NULL;


Now why does the member table have two stars?



  • The "inner" star means that the table stores pointers to nodes, not the nodes themselves.


  • The "outer" start is a handle to allocated memory. If your hash table were of a fixed size, for example always with 256 bins, you could define it as:



    struct node_s *table[256];


    If you passed this array around, it would become (or "decay into") a pointer to its first element, a struct node_s **, just as the array you got from malloc.



  • You access the contents of the l´bins via the linked lists and the head of linked list i is table->table[i].

You code has other problems:



  • What did you want to achieve with (table->table)++? This will make the handle to the allocated memory point not to the first element but tho the next one. After doing that hashnum times, *table->table will now be at the right node, but you will have lost the original handle, which you must retain, because you must pass it to free later when you clean up your hash table. Don't lose the handle to allocated memory! Use another local pointer instead.


  • You create a local node n and then make a link in your linked list with a pointer to that node. But the node n will be gone after you leave the function and the link will be "stale": It will point to invalid memory. You must also create memory for the node with malloc.


A simple implementation of your has table might be:



void set(hash_t table, char *key, int value)

unsigned int hashnum = hash(key) % table->bins;

// create (uninitialised) new node
struct node_s *nnew = malloc(sizeof(*nnew));

// initialise new node, point it to old head
nnew->key = strdup(key);
nnew->value = value;
nnew->link = table->table[hashnum];

// make the new node the new head
table->table[hashnum] = nnew;



This makes the new node the head of the linked list. This is not ideal, because if you overwrite items, the new ones will be found (which is good), but the old ones will still be in the table (which isn't good). But that, as they say, is left as an exercise to the reader.



(The strdup function isn't standard, but widely available. It also creates new memory, which you must free later, but it ensures, that the string "lives" (is still valid) after you have ceated the hash table.)



Please not how few stars there are in the code. If there is one star too few, it is in hash_t, where you have typecasted away the pointer nature.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068300%2fpointer-seg-faulting-although-i-malloc-ed-right%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Your hashtable works like this: You have bins bins and each bin is a linked list of key / value pairs. All items in a bin share the same hash code modulo the number of bins.



    You have probably created the table of bins when you created or initialised the hash table, something like this:



    table->table = malloc(table->bins * sizeof(*table->table);

    for (size_t i = 0; i < table->bins; i++) table->table[i] = NULL;


    Now why does the member table have two stars?



    • The "inner" star means that the table stores pointers to nodes, not the nodes themselves.


    • The "outer" start is a handle to allocated memory. If your hash table were of a fixed size, for example always with 256 bins, you could define it as:



      struct node_s *table[256];


      If you passed this array around, it would become (or "decay into") a pointer to its first element, a struct node_s **, just as the array you got from malloc.



    • You access the contents of the l´bins via the linked lists and the head of linked list i is table->table[i].

    You code has other problems:



    • What did you want to achieve with (table->table)++? This will make the handle to the allocated memory point not to the first element but tho the next one. After doing that hashnum times, *table->table will now be at the right node, but you will have lost the original handle, which you must retain, because you must pass it to free later when you clean up your hash table. Don't lose the handle to allocated memory! Use another local pointer instead.


    • You create a local node n and then make a link in your linked list with a pointer to that node. But the node n will be gone after you leave the function and the link will be "stale": It will point to invalid memory. You must also create memory for the node with malloc.


    A simple implementation of your has table might be:



    void set(hash_t table, char *key, int value)

    unsigned int hashnum = hash(key) % table->bins;

    // create (uninitialised) new node
    struct node_s *nnew = malloc(sizeof(*nnew));

    // initialise new node, point it to old head
    nnew->key = strdup(key);
    nnew->value = value;
    nnew->link = table->table[hashnum];

    // make the new node the new head
    table->table[hashnum] = nnew;



    This makes the new node the head of the linked list. This is not ideal, because if you overwrite items, the new ones will be found (which is good), but the old ones will still be in the table (which isn't good). But that, as they say, is left as an exercise to the reader.



    (The strdup function isn't standard, but widely available. It also creates new memory, which you must free later, but it ensures, that the string "lives" (is still valid) after you have ceated the hash table.)



    Please not how few stars there are in the code. If there is one star too few, it is in hash_t, where you have typecasted away the pointer nature.






    share|improve this answer



























      0














      Your hashtable works like this: You have bins bins and each bin is a linked list of key / value pairs. All items in a bin share the same hash code modulo the number of bins.



      You have probably created the table of bins when you created or initialised the hash table, something like this:



      table->table = malloc(table->bins * sizeof(*table->table);

      for (size_t i = 0; i < table->bins; i++) table->table[i] = NULL;


      Now why does the member table have two stars?



      • The "inner" star means that the table stores pointers to nodes, not the nodes themselves.


      • The "outer" start is a handle to allocated memory. If your hash table were of a fixed size, for example always with 256 bins, you could define it as:



        struct node_s *table[256];


        If you passed this array around, it would become (or "decay into") a pointer to its first element, a struct node_s **, just as the array you got from malloc.



      • You access the contents of the l´bins via the linked lists and the head of linked list i is table->table[i].

      You code has other problems:



      • What did you want to achieve with (table->table)++? This will make the handle to the allocated memory point not to the first element but tho the next one. After doing that hashnum times, *table->table will now be at the right node, but you will have lost the original handle, which you must retain, because you must pass it to free later when you clean up your hash table. Don't lose the handle to allocated memory! Use another local pointer instead.


      • You create a local node n and then make a link in your linked list with a pointer to that node. But the node n will be gone after you leave the function and the link will be "stale": It will point to invalid memory. You must also create memory for the node with malloc.


      A simple implementation of your has table might be:



      void set(hash_t table, char *key, int value)

      unsigned int hashnum = hash(key) % table->bins;

      // create (uninitialised) new node
      struct node_s *nnew = malloc(sizeof(*nnew));

      // initialise new node, point it to old head
      nnew->key = strdup(key);
      nnew->value = value;
      nnew->link = table->table[hashnum];

      // make the new node the new head
      table->table[hashnum] = nnew;



      This makes the new node the head of the linked list. This is not ideal, because if you overwrite items, the new ones will be found (which is good), but the old ones will still be in the table (which isn't good). But that, as they say, is left as an exercise to the reader.



      (The strdup function isn't standard, but widely available. It also creates new memory, which you must free later, but it ensures, that the string "lives" (is still valid) after you have ceated the hash table.)



      Please not how few stars there are in the code. If there is one star too few, it is in hash_t, where you have typecasted away the pointer nature.






      share|improve this answer

























        0












        0








        0







        Your hashtable works like this: You have bins bins and each bin is a linked list of key / value pairs. All items in a bin share the same hash code modulo the number of bins.



        You have probably created the table of bins when you created or initialised the hash table, something like this:



        table->table = malloc(table->bins * sizeof(*table->table);

        for (size_t i = 0; i < table->bins; i++) table->table[i] = NULL;


        Now why does the member table have two stars?



        • The "inner" star means that the table stores pointers to nodes, not the nodes themselves.


        • The "outer" start is a handle to allocated memory. If your hash table were of a fixed size, for example always with 256 bins, you could define it as:



          struct node_s *table[256];


          If you passed this array around, it would become (or "decay into") a pointer to its first element, a struct node_s **, just as the array you got from malloc.



        • You access the contents of the l´bins via the linked lists and the head of linked list i is table->table[i].

        You code has other problems:



        • What did you want to achieve with (table->table)++? This will make the handle to the allocated memory point not to the first element but tho the next one. After doing that hashnum times, *table->table will now be at the right node, but you will have lost the original handle, which you must retain, because you must pass it to free later when you clean up your hash table. Don't lose the handle to allocated memory! Use another local pointer instead.


        • You create a local node n and then make a link in your linked list with a pointer to that node. But the node n will be gone after you leave the function and the link will be "stale": It will point to invalid memory. You must also create memory for the node with malloc.


        A simple implementation of your has table might be:



        void set(hash_t table, char *key, int value)

        unsigned int hashnum = hash(key) % table->bins;

        // create (uninitialised) new node
        struct node_s *nnew = malloc(sizeof(*nnew));

        // initialise new node, point it to old head
        nnew->key = strdup(key);
        nnew->value = value;
        nnew->link = table->table[hashnum];

        // make the new node the new head
        table->table[hashnum] = nnew;



        This makes the new node the head of the linked list. This is not ideal, because if you overwrite items, the new ones will be found (which is good), but the old ones will still be in the table (which isn't good). But that, as they say, is left as an exercise to the reader.



        (The strdup function isn't standard, but widely available. It also creates new memory, which you must free later, but it ensures, that the string "lives" (is still valid) after you have ceated the hash table.)



        Please not how few stars there are in the code. If there is one star too few, it is in hash_t, where you have typecasted away the pointer nature.






        share|improve this answer













        Your hashtable works like this: You have bins bins and each bin is a linked list of key / value pairs. All items in a bin share the same hash code modulo the number of bins.



        You have probably created the table of bins when you created or initialised the hash table, something like this:



        table->table = malloc(table->bins * sizeof(*table->table);

        for (size_t i = 0; i < table->bins; i++) table->table[i] = NULL;


        Now why does the member table have two stars?



        • The "inner" star means that the table stores pointers to nodes, not the nodes themselves.


        • The "outer" start is a handle to allocated memory. If your hash table were of a fixed size, for example always with 256 bins, you could define it as:



          struct node_s *table[256];


          If you passed this array around, it would become (or "decay into") a pointer to its first element, a struct node_s **, just as the array you got from malloc.



        • You access the contents of the l´bins via the linked lists and the head of linked list i is table->table[i].

        You code has other problems:



        • What did you want to achieve with (table->table)++? This will make the handle to the allocated memory point not to the first element but tho the next one. After doing that hashnum times, *table->table will now be at the right node, but you will have lost the original handle, which you must retain, because you must pass it to free later when you clean up your hash table. Don't lose the handle to allocated memory! Use another local pointer instead.


        • You create a local node n and then make a link in your linked list with a pointer to that node. But the node n will be gone after you leave the function and the link will be "stale": It will point to invalid memory. You must also create memory for the node with malloc.


        A simple implementation of your has table might be:



        void set(hash_t table, char *key, int value)

        unsigned int hashnum = hash(key) % table->bins;

        // create (uninitialised) new node
        struct node_s *nnew = malloc(sizeof(*nnew));

        // initialise new node, point it to old head
        nnew->key = strdup(key);
        nnew->value = value;
        nnew->link = table->table[hashnum];

        // make the new node the new head
        table->table[hashnum] = nnew;



        This makes the new node the head of the linked list. This is not ideal, because if you overwrite items, the new ones will be found (which is good), but the old ones will still be in the table (which isn't good). But that, as they say, is left as an exercise to the reader.



        (The strdup function isn't standard, but widely available. It also creates new memory, which you must free later, but it ensures, that the string "lives" (is still valid) after you have ceated the hash table.)



        Please not how few stars there are in the code. If there is one star too few, it is in hash_t, where you have typecasted away the pointer nature.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 18:14









        M OehmM Oehm

        21.8k31832




        21.8k31832





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068300%2fpointer-seg-faulting-although-i-malloc-ed-right%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко