CS50 - LOAD - Get random character from no where when trying to execute load












0















I am new to C programming. I am trying to do the pset5 in CS50 while trying to understand the concepts of memory, linked list and hashtable. I wrote the code and it compiled but there seems to be something wrong because every time I tried to execute the code it returns some garbage value. Could anyone please help me with that? Many thanks.



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

#include "dictionary.h"

#define DICTIONARY "dictionaries/small"

typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;

int hash(char *word);

int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);

//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the libraryn");
return 1;
}

int index = 0;
char word[LENGTH + 1];

for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;

if (c == 'n')
{
int table = hash(word);
printf("%dn", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;

printf("Node: %sn", newnode->WORD);
index = 0;

//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}

//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}


int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}


enter image description here










share|improve this question

























  • for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

    – Antti Haapala
    Nov 15 '18 at 20:44






  • 1





    btw the output you should include as a code block, not as an image...

    – Antti Haapala
    Nov 15 '18 at 20:45






  • 1





    Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

    – Antti Haapala
    Nov 15 '18 at 20:49











  • @AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

    – Tls2018
    Nov 15 '18 at 21:49
















0















I am new to C programming. I am trying to do the pset5 in CS50 while trying to understand the concepts of memory, linked list and hashtable. I wrote the code and it compiled but there seems to be something wrong because every time I tried to execute the code it returns some garbage value. Could anyone please help me with that? Many thanks.



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

#include "dictionary.h"

#define DICTIONARY "dictionaries/small"

typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;

int hash(char *word);

int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);

//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the libraryn");
return 1;
}

int index = 0;
char word[LENGTH + 1];

for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;

if (c == 'n')
{
int table = hash(word);
printf("%dn", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;

printf("Node: %sn", newnode->WORD);
index = 0;

//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}

//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}


int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}


enter image description here










share|improve this question

























  • for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

    – Antti Haapala
    Nov 15 '18 at 20:44






  • 1





    btw the output you should include as a code block, not as an image...

    – Antti Haapala
    Nov 15 '18 at 20:45






  • 1





    Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

    – Antti Haapala
    Nov 15 '18 at 20:49











  • @AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

    – Tls2018
    Nov 15 '18 at 21:49














0












0








0








I am new to C programming. I am trying to do the pset5 in CS50 while trying to understand the concepts of memory, linked list and hashtable. I wrote the code and it compiled but there seems to be something wrong because every time I tried to execute the code it returns some garbage value. Could anyone please help me with that? Many thanks.



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

#include "dictionary.h"

#define DICTIONARY "dictionaries/small"

typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;

int hash(char *word);

int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);

//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the libraryn");
return 1;
}

int index = 0;
char word[LENGTH + 1];

for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;

if (c == 'n')
{
int table = hash(word);
printf("%dn", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;

printf("Node: %sn", newnode->WORD);
index = 0;

//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}

//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}


int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}


enter image description here










share|improve this question
















I am new to C programming. I am trying to do the pset5 in CS50 while trying to understand the concepts of memory, linked list and hashtable. I wrote the code and it compiled but there seems to be something wrong because every time I tried to execute the code it returns some garbage value. Could anyone please help me with that? Many thanks.



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

#include "dictionary.h"

#define DICTIONARY "dictionaries/small"

typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;

int hash(char *word);

int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);

//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the libraryn");
return 1;
}

int index = 0;
char word[LENGTH + 1];

for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;

if (c == 'n')
{
int table = hash(word);
printf("%dn", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;

printf("Node: %sn", newnode->WORD);
index = 0;

//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}

//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}


int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}


enter image description here







c memory linked-list hashtable cs50






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 20:46









Antti Haapala

84.5k16161202




84.5k16161202










asked Nov 15 '18 at 20:37









Tls2018Tls2018

41




41













  • for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

    – Antti Haapala
    Nov 15 '18 at 20:44






  • 1





    btw the output you should include as a code block, not as an image...

    – Antti Haapala
    Nov 15 '18 at 20:45






  • 1





    Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

    – Antti Haapala
    Nov 15 '18 at 20:49











  • @AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

    – Tls2018
    Nov 15 '18 at 21:49



















  • for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

    – Antti Haapala
    Nov 15 '18 at 20:44






  • 1





    btw the output you should include as a code block, not as an image...

    – Antti Haapala
    Nov 15 '18 at 20:45






  • 1





    Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

    – Antti Haapala
    Nov 15 '18 at 20:49











  • @AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

    – Tls2018
    Nov 15 '18 at 21:49

















for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

– Antti Haapala
Nov 15 '18 at 20:44





for (int c = fgetc(dic); c != EOF; c = fgetc(dic)) is customarily written as int c; while ((c = fgetc(dic)) != EOF)

– Antti Haapala
Nov 15 '18 at 20:44




1




1





btw the output you should include as a code block, not as an image...

– Antti Haapala
Nov 15 '18 at 20:45





btw the output you should include as a code block, not as an image...

– Antti Haapala
Nov 15 '18 at 20:45




1




1





Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

– Antti Haapala
Nov 15 '18 at 20:49





Another issue is that try adding 3 words with the same initial letter - your hash table linking is incorrect.

– Antti Haapala
Nov 15 '18 at 20:49













@AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

– Tls2018
Nov 15 '18 at 21:49





@AnttiHaapala Thank you very much for your comments. They are very helpful! This is my first question so I was struggling to include a code also so sorry for the image. And I do not really get your comment on the 3 words with the same initial letter... I am just trying to run with a trial dictionary.

– Tls2018
Nov 15 '18 at 21:49












2 Answers
2






active

oldest

votes


















2














Your code has serious problems that result in undefined behavior.



Two of them are the result of this line:



node **HASHTABLE = malloc(sizeof(node) * 26);


That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).



So, you should replace it with something like:



node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.



That problem, while technically undefined behavior, likely wouldn't cause any problems.



However, there's still a problem with



node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


that will cause problems - and serious ones.



That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:



    if (HASHTABLE[table] == NULL)


Meaning this points off to somewhere unknown:



    HASHTABLE[table]->next = newnode;


And that will cause all kinds of problems.



The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():



node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );


Until that's fixed, any results from your entire program are questionable, at best.






share|improve this answer


























  • Thank you for your comment. It helps me understand a lot more about those functions!

    – Tls2018
    Nov 15 '18 at 21:49



















2














The reason for the garbage is that you didn't null-terminate the string:



strcpy(newnode->WORD, word);


strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with



word[index] = 0;


before the strcpy.



Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.





BTW, next you will notice that



HASHTABLE[table]->next = newnode;


wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with



newnode->next = HASHTABLE[table];
HASHTABLE[table] = newnode;


There need not be any special condition for inserting the first node to a bucket.






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%2f53327543%2fcs50-load-get-random-character-from-no-where-when-trying-to-execute-load%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Your code has serious problems that result in undefined behavior.



    Two of them are the result of this line:



    node **HASHTABLE = malloc(sizeof(node) * 26);


    That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).



    So, you should replace it with something like:



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.



    That problem, while technically undefined behavior, likely wouldn't cause any problems.



    However, there's still a problem with



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    that will cause problems - and serious ones.



    That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:



        if (HASHTABLE[table] == NULL)


    Meaning this points off to somewhere unknown:



        HASHTABLE[table]->next = newnode;


    And that will cause all kinds of problems.



    The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():



    node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );


    Until that's fixed, any results from your entire program are questionable, at best.






    share|improve this answer


























    • Thank you for your comment. It helps me understand a lot more about those functions!

      – Tls2018
      Nov 15 '18 at 21:49
















    2














    Your code has serious problems that result in undefined behavior.



    Two of them are the result of this line:



    node **HASHTABLE = malloc(sizeof(node) * 26);


    That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).



    So, you should replace it with something like:



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.



    That problem, while technically undefined behavior, likely wouldn't cause any problems.



    However, there's still a problem with



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    that will cause problems - and serious ones.



    That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:



        if (HASHTABLE[table] == NULL)


    Meaning this points off to somewhere unknown:



        HASHTABLE[table]->next = newnode;


    And that will cause all kinds of problems.



    The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():



    node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );


    Until that's fixed, any results from your entire program are questionable, at best.






    share|improve this answer


























    • Thank you for your comment. It helps me understand a lot more about those functions!

      – Tls2018
      Nov 15 '18 at 21:49














    2












    2








    2







    Your code has serious problems that result in undefined behavior.



    Two of them are the result of this line:



    node **HASHTABLE = malloc(sizeof(node) * 26);


    That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).



    So, you should replace it with something like:



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.



    That problem, while technically undefined behavior, likely wouldn't cause any problems.



    However, there's still a problem with



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    that will cause problems - and serious ones.



    That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:



        if (HASHTABLE[table] == NULL)


    Meaning this points off to somewhere unknown:



        HASHTABLE[table]->next = newnode;


    And that will cause all kinds of problems.



    The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():



    node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );


    Until that's fixed, any results from your entire program are questionable, at best.






    share|improve this answer















    Your code has serious problems that result in undefined behavior.



    Two of them are the result of this line:



    node **HASHTABLE = malloc(sizeof(node) * 26);


    That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).



    So, you should replace it with something like:



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.



    That problem, while technically undefined behavior, likely wouldn't cause any problems.



    However, there's still a problem with



    node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );


    that will cause problems - and serious ones.



    That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:



        if (HASHTABLE[table] == NULL)


    Meaning this points off to somewhere unknown:



        HASHTABLE[table]->next = newnode;


    And that will cause all kinds of problems.



    The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():



    node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );


    Until that's fixed, any results from your entire program are questionable, at best.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 15 '18 at 20:57

























    answered Nov 15 '18 at 20:51









    Andrew HenleAndrew Henle

    20.4k31435




    20.4k31435













    • Thank you for your comment. It helps me understand a lot more about those functions!

      – Tls2018
      Nov 15 '18 at 21:49



















    • Thank you for your comment. It helps me understand a lot more about those functions!

      – Tls2018
      Nov 15 '18 at 21:49

















    Thank you for your comment. It helps me understand a lot more about those functions!

    – Tls2018
    Nov 15 '18 at 21:49





    Thank you for your comment. It helps me understand a lot more about those functions!

    – Tls2018
    Nov 15 '18 at 21:49













    2














    The reason for the garbage is that you didn't null-terminate the string:



    strcpy(newnode->WORD, word);


    strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with



    word[index] = 0;


    before the strcpy.



    Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.





    BTW, next you will notice that



    HASHTABLE[table]->next = newnode;


    wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with



    newnode->next = HASHTABLE[table];
    HASHTABLE[table] = newnode;


    There need not be any special condition for inserting the first node to a bucket.






    share|improve this answer






























      2














      The reason for the garbage is that you didn't null-terminate the string:



      strcpy(newnode->WORD, word);


      strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with



      word[index] = 0;


      before the strcpy.



      Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.





      BTW, next you will notice that



      HASHTABLE[table]->next = newnode;


      wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with



      newnode->next = HASHTABLE[table];
      HASHTABLE[table] = newnode;


      There need not be any special condition for inserting the first node to a bucket.






      share|improve this answer




























        2












        2








        2







        The reason for the garbage is that you didn't null-terminate the string:



        strcpy(newnode->WORD, word);


        strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with



        word[index] = 0;


        before the strcpy.



        Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.





        BTW, next you will notice that



        HASHTABLE[table]->next = newnode;


        wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with



        newnode->next = HASHTABLE[table];
        HASHTABLE[table] = newnode;


        There need not be any special condition for inserting the first node to a bucket.






        share|improve this answer















        The reason for the garbage is that you didn't null-terminate the string:



        strcpy(newnode->WORD, word);


        strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with



        word[index] = 0;


        before the strcpy.



        Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.





        BTW, next you will notice that



        HASHTABLE[table]->next = newnode;


        wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with



        newnode->next = HASHTABLE[table];
        HASHTABLE[table] = newnode;


        There need not be any special condition for inserting the first node to a bucket.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 21:01

























        answered Nov 15 '18 at 20:54









        Antti HaapalaAntti Haapala

        84.5k16161202




        84.5k16161202






























            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%2f53327543%2fcs50-load-get-random-character-from-no-where-when-trying-to-execute-load%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

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly