c - 按顺序插入字符串数组

标签 c arrays string pointers insertion

我正在尝试编写一个插入到字典(字符串数组)中的函数,但按字母(词汇)顺序插入,但我遇到了大小为 8 的无效读取错误,我并不完全知道为什么。

这是我的代码:

int insertWord(char **array, int *count, char word[])
{
    char *wordPtr;

    wordPtr = (char *)malloc((strlen(word) + 1) * sizeof(char));
    if (wordPtr == NULL)
    {
        fprintf(stderr,"    Malloc of array[%d] failed!\n", *count);
        return -1;
    }
    /* Memory for this word has been allocated, so copy characters
       and insert into array */

    strcpy(wordPtr, word);

    // Iterate through the word array
    // Check if str1 > other strings
    // Lower ascii value = earlier in the alphabet
    // Will return neg value if str1 < str2 (str1 comes before str2)
    // Will return 0 if they are equal
    // Will return pos value if str1 > str2 (str1 comes after str2)
    // Check for an element that comes after the given word in the alphabet
    bool greaterElementFound = false;
    int indexLoc = *count;
    for(int i = 0 ; i < *count ; i ++){
            // If compare is a neg #, that means that wordPtr comes before array[i]
            // So array[i] must be shifted right, and wordPtr must be inserted in its place
            if(strcasecmp(wordPtr, array[i]) < 0){
                    greaterElementFound = true;
                    indexLoc = i;
                    break;
            }
    }
    if(greaterElementFound == true){
            // Account for overwrite of last element
            array[*count+1] = array[*count];
            // Shift all elements over from indexLoc to *count
            for(int i = *count; i > indexLoc; i--){
                    array[i] = array[i-1];
            }
    }
    array[indexLoc] = wordPtr;

    (*count)++;

return 0;
}

我在 valgrind 中遇到了一个被抑制的错误:

==4123== ERROR SUMMARY: 2 errors from 1 contexts (suppressed: 4 from 4)
==4123== 
==4123== 2 errors in context 1 of 1:
==4123== Invalid write of size 8
==4123==    at 0x401056: insertWord (in /import/linux/home/jball2/CLab/lab2)
==4123==    by 0x400E3E: loadArray (in /import/linux/home/jball2/CLab/lab2)
==4123==    by 0x400AAE: main (in /import/linux/home/jball2/CLab/lab2)
==4123==  Address 0x51b1450 is 0 bytes after a block of size 400 alloc'd
==4123==    at 0x4C2779D: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4123==    by 0x400D91: loadArray (in /import/linux/home/jball2/CLab/lab2)
==4123==    by 0x400AAE: main (in /import/linux/home/jball2/CLab/lab2)

如果有人能指出正确的方向,我将不胜感激,谢谢。

------------------------------------供引用-------- ----------------------------------
这是我的 loadArray() 函数:

int loadArray(char *inFileName, char ***array, int *count, int *capacity)
{
FILE *inFile;
char word[WORD_LENGTH];  /* this is the ONLY auto array we'll need */

if ((inFile = fopen(inFileName, "r")) == NULL)
{
    fprintf(stderr,"Error opening input file, %s\n", inFileName);
    return -1;
}

*array = (char **)malloc(*capacity * sizeof(char*));
if (*array == NULL)
{
    fprintf(stderr, "Malloc of array in loadArray failed!\n");
    return -1;
}

printf("Reading file %s (each . is 5000 words read)\n", inFileName);

*count = 0;
while (fscanf(inFile, "%s", word) == 1)
{
    if (*count >= *capacity)
    {
    /* call a function that will double the size of the array and copy its contents */
    doubleArray(array, count, capacity);
    }

    if (insertWord(*array, count, word) != 0)
    {
        fprintf(stderr,"    Insert returned an error!\n");
        fclose(inFile);
        return 1;
    }

    if (*count % 5000 == 0)
    {
        printf(".");
        fflush(stdout);  /* stdout is buffered, so have to force flush */
    }
}

fclose(inFile);

return 0;
}

最佳答案

如果 *countarray 中元素的数量(已使用和未使用),则此

        array[*count+1] = array[*count];

将超越数组的边界。 array 可以是从 0 到 *count - 1 的索引。

如果*countarray中使用的元素个数,那么扩展前需要查看array的总大小。

array 的其他索引也可以是 >= *count。仔细看看它们。

如果在调用 insertWord 的代码中对数组进行 m​​alloc,您将需要重新分配它以调整 array 的大小。

无论如何,需要了解如何在调用 insertWord 的代码中创建数组才能进行智能注释。


好的,新信息。考虑 capacity=100 和 count=99 的情况,您调用 insertWord 并需要追加新词。这个

array[*count+1] = array[*count];

成为

array[100] = array[99];

索引 100 太大了;容量为 100,有效索引为 0-99。 您可以通过更改来解决此问题

if (*count >= *capacity) // double array

if (*count >= *capacity-1) // double array

关于c - 按顺序插入字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456212/

相关文章:

c - 除以零中断错误 "using float variables"

c - free() 使代码崩溃

JAVA删除字符串中最后一个 "*"

Java String - 查看一个字符串是否只包含数字和字符而不包含单词?

java - 从字符串中删除选定字符

c - 素数查找器代码

具有 C 中指针结构的 Calloc

java - 将字符串数组转换为 ArrayList<String>

arrays - 将 Scala 数组转换为唯一排序列表的有效方法

c - 我如何计算没有。字符串数组中的字符串?