使用malloc设置字符串数组,然后清除它 [英] use malloc to set an array of strings then clear it

查看:60
本文介绍了使用malloc设置字符串数组,然后清除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用malloc创建一个字符串数组,然后清除所有分配的内存,我相信我正确地使用了malloc,但是当我尝试清除它时,我不明白我在做什么错了:

I want to make an array of string using malloc, and then clear ALL the allocated memory, I believe that I use malloc correct but I can't understand what I'm doing wrong when I try to clear it:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void print_arr(char* arr[]);
void clear_arr(char* arr[], int size);
int main()
{
    int number = 10;
    char **myarr = malloc((number+1)*sizeof(char*));
    for (int i = 0; i <= number; i++)
    {
        myarr[i]=NULL;
    }
    for (int i = 0; i < number; i++)
    {
        char str[] = "word";
        int len = strlen(str);
        myarr[i]=malloc((len+1)*sizeof(char));
        strcpy(myarr[i], str);
    }
    print_arr(myarr);
    clear_arr(myarr, number);
    print_arr(myarr);
    free(myarr);

   return 0; 
}
void print_arr(char* arr[])
{
    for (int i = 0; arr[i] != NULL; i++)
    {
        printf("%s\n",arr[i]);
    }

}
void clear_arr(char* arr[], int size)
{
    for (int i = 0; i < size; i++)
    {
        free(arr[i]);
    }

}

但我的数字= 3的输出是:

but my output for number = 3 is:

word
word
word
Pi╛
word
word

看起来只有数组的第一个单元"释放了,而另一个没有受到影响.我的clear_arr函数怎么了?如果要紧的话,我正在使用VScode进行编译...

it's look like that only the first "cell" of the array is getting free and the other doesn't effected. what wrong with my clear_arr function? I'm using VScode to compile if that matters...

推荐答案

那是因为您尝试打印一些您将释放的东西. free 函数取消分配内存,但是您仍然在数组中具有地址.

That's because you try to print something that you free'd. The free function deallocate the memory but you still have the address in the array.

您可以做的是:

void clear_arr(char* arr[], int size)
{
    for (int i = 0; i < size; i++)
    {
        free(arr[i]);
        arr[i] = NULL;
    }

}

这样,打印功能将不会遍历一系列自由指针.

This way, the print function won't loop through an array of free'd pointers.

有一种更好的方法来分配和复制字符串,可以使用函数 strdup .

There is a better way to malloc and copy a string, you can use the function strdup.

您的代码可以通过以下方式进行优化:

Your code could be optimized this way:

int number = 10;
char **myarr = malloc((number+1)*sizeof(char*));
for (int i = 0; i < number; i++)
{
  myarr[i] = strdup("word");
}

myarr[number] = NULL;

这篇关于使用malloc设置字符串数组,然后清除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆