c - 我应该如何释放指向字符串的指针数组?

标签 c arrays string memory-management

我包括了所有的代码,所以如果你有任何意见我想学习!

该函数正在接收一个字符串并创建一个字符串指针数组;每个字符串都包含以所选字母开头的单词。

我的问题是函数 free_string() 出现错误!

我知道这是释放矩阵的方法,所以也许在那之前就出了问题?

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

void main()
{
    char str[SIZE],leteer,**string;
    int size=0;
    printf("please enter the string\n");
    gets(str);
    printf("please enter the letter\n");
    scanf("%c",&leteer);
    string=create_strings_from_letter(str, leteer, &size);
    print_string(string,size);
    free_string(string,size);
}

char ** create_strings_from_letter(char *str, char letter, int * size)

{

    char **string_of_letters;
    char *read = str,*write;
    int count=0,i=0;
    while (*read)//cheaking how much strings to allocate//
    {
        if (*read == tolower(letter)|| *read == toupper(letter))
        {
            (*size)++;
            for (; *read && *read != ' '; read++);
        }
        for (; *read && *read != ' '; read++);
        read++;
    }
    string_of_letters = (char**)malloc((*size)*sizeof(char*));
    read = str;
    while (*read)
    {
        for (; *read && *read != tolower(letter) && *read != toupper(letter);read++);
        if (*read)
        {
            write = read;
            for (; *read && *read != ' '; read++, count++);
            string_of_letters[i] = (char*)malloc((count) * sizeof(char));
            strncpy(string_of_letters[i], write,count);
            string_of_letters[i][count] = '\0';
            count = 0;
            i++;
        }
        else
            break;
    }
    return string_of_letters;


}

void free_string(char ** string, int size)

{

    int i;
    for (i = 0;i<size; i++)
        free(string[i]);

    free(string);
}

最佳答案

从评论中,您似乎找到了错误的根源,即写入越界的内存地址。所以我想在评论中解决你的其他问题。

what bothers is that he did not warn me about exceeded the limits of the array why is that?

这取决于您设置的编译器选项。一些编译器有设置警告级别和优化级别的选项。如果这样做,可以看到警告。

例如,对于 GCC,如果将警告级别选项设置为 -Wall(许多)并将优化级别设置为 -O2(完整),当您尝试写入越界内存地址时,您会收到警告。

警告将是这样的:

warning: array subscript is above array bounds [-Warray-bounds]

关于c - 我应该如何释放指向字符串的指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053454/

相关文章:

将 unsigned char * (uint8_t *) 转换为 const char *

c - 取消引用指向不完整类型的指针

c - 在 C 中,如何用特定模式初始化数组?

java - 如何根据一列对一维(或二维)数组(多维)进行排序?

c# - 检查数组项的字符串并匹配它

c++ - 在 C++ 中确定 getline() 起点

c++ - 指向一个数组以获取其所有内容

c - 使用 ioctl 更改 autorepeat 的值

python - 从多个 csv 文件创建二维矩阵

c++ - 从控制台获取字符串但不知道长度