简体   繁体   English

当我尝试将数组中的元素分配给 C 中数据结构中的相同类型值时,为什么会出现分段错误?

[英]Why am I getting a segmentation fault when I try to assign an element from an array to a same type value in my data structure in C?

I'm writing a program that is supposed to assign characters from a buffer into a hash-table.我正在编写一个程序,该程序应该将缓冲区中的字符分配到哈希表中。 I ran valgrind on my program and it signals to a particular line (tmp->word = buffer[i];) and keeps telling me there is a segmentation fault there.我在我的程序上运行了 valgrind,它向特定行发出信号 (tmp->word = buffer[i];),并一直告诉我那里存在分段错误。

I tried hardcoding the problem line to (tmp->word = 'c';) but the compiler rejected that implementation.我尝试将问题行硬编码为 (tmp->word = 'c';) 但编译器拒绝了该实现。 I checked to see if the buffer array was initialized, which it was.我检查了缓冲区数组是否已初始化,确实如此。 The program compiles when the problem line is changed to (tmp->word = buffer[i];) but that leads back to a segmentation fault.当问题行更改为 (tmp->word = buffer[i];) 时程序会编译,但这会导致返回分段错误。 I have also tried printing the character field in my data structure after I assign it, but the segmentation fault occurs before that can happen.我也试过在分配后在我的数据结构中打印字符字段,但是在这之前就发生了分段错误。 This is what I've written so far.这是我到目前为止所写的。 Any help would be greatly appreciated.任何帮助将不胜感激。

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



typedef struct node
{
    struct node* next;
    char word;
}
node;

void unload(node* current);

int main(void)
{
        node* table[26];

        char buffer[5] = "Hello";
        printf("%s\n", buffer);
        int index = tolower(buffer[0]) - 'a';
        node* tmp = table[index];
        for(int i = 0, n = strlen(buffer); i < n - 1; tmp = tmp->next)
        {
            tmp->word = buffer[i];
            printf("%c\n", tmp->word);
            i++;

        }

        //follows word that was input
        index = tolower(buffer[0]) - 'a';
        for(int j = 0; j < 1; j++)
        {
            tmp = table[index]->next;
            unload(tmp);
        }


}

void unload(node* current)
{
    if (current->next != NULL)
        {
            unload(current->next);
        }

    free(current);
}

As is the comments the main problem is an array of uninitialized pointers.正如评论一样,主要问题是未初始化指针数组。 As "intuitive way" while you are coding you may think the once you typed node* table[26];作为编码时的“直观方式”,您可能会认为一旦键入node* table[26]; as int type variables, this will be set to NULL automatically as a pattern behavior or something.But it points to a random location in memory when you declare it.作为int类型变量,这将作为模式行为或其他内容自动设置为NULL但是当您声明它时,它指向 memory 中的随机位置。 It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system.它可能指向系统堆栈、全局变量、程序代码空间或操作系统。

So, you must give them something to point to and in this case is a NULL .所以,你必须给他们一些东西来指向,在这种情况下是NULL You can do it like this node* table[26] = {NULL};你可以像这样node* table[26] = {NULL}; . . Another point is when you type char buffer[5] = "Hello";另一点是当你输入char buffer[5] = "Hello"; . . The char buffer[5] essentially is a pointer pointing to a memory address that the system saves so you can put your string. char buffer[5]本质上是一个指向系统保存的 memory 地址的指针,因此您可以放置字符串。 The memory is saved in blocks so when you type char buffer[1] for example you "jump" to the second part of the entire block which represents the string. memory 保存在块中,因此当您键入char buffer[1]时,例如您“跳转”到代表字符串的整个块的第二部分。

When you do char buffer[5] = "Hello";当你做char buffer[5] = "Hello"; " it's sounds like " you are trying to make the Hello string fit in the last piece of the block. “这听起来像是”您正在尝试使Hello字符串适合块的最后一部分。 To fix this just type char buffer[6] = {"Hello"};要解决此问题,只需键入char buffer[6] = {"Hello"}; (Because you need n+1 of size, you have to include the \0 character). (因为您需要 n+1 的大小,所以您必须包含\0字符)。 And it will fit properly.它会很合适。 Now i think you can figure out how to do the rest.现在我认为您可以弄清楚如何执行 rest。

As was mentioned before in the comments and answer, my array of pointers wasn't initialized.正如之前在评论和回答中提到的,我的指针数组没有被初始化。 This was a part of the main problem I had which was experiencing a segmentation fault when I tried to assign table[i]->word and table[i]->next a value.这是我遇到的主要问题的一部分,当我尝试分配table[i]->wordtable[i]->next一个值时遇到分段错误。 No memory was allocated for the nodes in the table so I went and did that which fixed most the problems, Something I learned, however, is that I could not assign a string to table[i]->word which is an array of characters in my now less buggy program, and instead had to use strcpy to read a string into that memory space (please correct me if I'm wrong on that).没有为表中的节点分配 memory 所以我去做了解决大部分问题的事情,但是我学到的是我无法将字符串分配给table[i]->word这是一个字符数组在我现在错误较少的程序中,而是不得不使用 strcpy 将字符串读入 memory 空间(如果我错了,请纠正我)。 Thank you all for your help and advice, it was really useful, Posted below is the version of my program that actually works save for a conditional that I need to implement thanks to your guys' help!谢谢大家的帮助和建议,它真的很有用,下面发布的是我的程序的实际工作版本,除了我需要实施的条件,感谢你们的帮助! Again, thank you very much!再次,非常感谢!

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

#define LENGTH 45
#define CAPACITY 26

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

int hash(char* current);
void unload(node* current);


int main(void)
{
    //const unsigned int N = 26;
    node* table[CAPACITY];

    for(int i = 0; i < CAPACITY; i++)
    {
        table[i] = malloc(sizeof(node)); // this was table[i]->next before. I didn't allocate memory for this node and then tried to defrefernce to a field in a node I though existed
        if(table[i] == NULL)
        {
            printf("Could not allocate memory for hashtable node");
            for(int j = 0; j < CAPACITY; j++)
            {
                unload(table[i]);
            }
            return 1;
        }
        table[i]->next = NULL; //just reinitializing the value here so that its not a garbage value
        //table[i]->word = "NULL";
    }

    int q = 0;
    while(q < 3) //ths will be chnaged so that we're reading from a file into a buffer and that get_string is gone, hash() stays tho
    {
        char* name = get_string("Here: ");
        int index = hash(name);

        if(table[index]->next == NULL)
        {
            node* cursor = malloc(sizeof(node)); //I'm not executing this if the hash code is the same
            table[index]->next = cursor;
            strcpy(cursor->word, name);  //for some reason you can't just assign a value to an element in an array in a data structure, seems that you need to read the data you want to assign into the location of the element
            //cursor->word = name;
            cursor->next = NULL;
            printf("%s\n", cursor->word);
        }

        q++;
    }


    for(int i = 0; i < CAPACITY; i++)
    {
        unload(table[i]); //wonder why I don't need to do table[i]->next? does this not free the hash table after the first iteration?
                          // the answer to above is because we are only freeing the node which is that element in the array, not the array itself
    }


        strcpy(table[6]->word, "Zebra");
        printf("%lu\n", sizeof(table[6]));
        printf("%s\n", table[6]->word);

    /*for(int i = 0; i < CAPACITY; i++)
    {
        unload(table[i]); //only problem here is that it will eventually free the hash table itself after the first linked list
    }*/



}

int hash(char* current)
{
    int index = tolower(current[0]) - 'a';
    return index;
}

void unload(node* current)
{
        if (current->next != NULL)
        {
            unload(current->next);
        }

        free(current);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试将新节点添加到链接列表时,为什么会出现细分错误? - Why am I getting a Segmentation fault when I try to add a new node to my linked list? C - 为什么我会出现分段错误? - C - Why am I getting a segmentation fault? 为什么当我在 c 中分配 2048 * 2048 int 数组时出现分段错误 - why am I getting segmentation fault when I alloc a 2048 * 2048 int array in c 从控制台读取字符并将其存储在数组中时,为什么会出现分段错误? - Why am I getting a segmentation fault when reading characters from console and storing in an array? 尝试运行测试时,为什么会出现“ Segmentation Fault”错误? - Why am I getting a “Segmentation Fault” error when I try to run the tests? 当我尝试使用递归打印结构时,为什么会出现分段错误(核心已转储)? - Why am i getting Segmentation fault (core dumped) when i try to print a struct using recursion? 实现堆栈数据结构时出现分段错误 - I am Getting segmentation fault while implementing Stack Data Structure 在CI中出现细分错误,我不知道为什么 - In C I am getting segmentation fault, i do not know why 为什么在运行此代码时会出现分段错误? - why am i getting segmentation fault when i run this code? 运行此代码时为什么会出现分段错误? - Why am I getting a segmentation fault when I run this code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM