当我在 c [重复] 中使用 free() 时程序崩溃

问题描述 投票:0回答:1

这个作业我真的需要帮助:

"写一个 void 类型的函数,它接受一个字符数组并创建两个新数组 (动态的)。对于其中一个,该函数从原始字母数组中复制小写字母,并将大写字母复制到另一个。 可以假设内存中有足够的空间来分配数组。 这两个新数组必须在 main 中打印,并在程序结束时释放内存”

根据我的理解,现在您需要释放 arrys 和 main 的末尾。 现在我创造了一些有用的东西,但是当我试图释放两个 arrys 时,它只会粉碎一切。 我真的需要一些帮助来了解该怎么做。

我得到运行时错误但没有免费它工作正常。

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

void targil_2(char* str, char** big, char** small);
void printArr(char* str);

enter code here

int main()
{

    char larr[] = { 'i','T','O','l','E','i','k','A','e','s','T','P','I','\0' };

    char* small_letters=NULL;
    char* big_letters=NULL;

    targil_2(larr,&big_letters,&small_letters);

    printArr(larr);
    printArr(small_letters);
    printArr(big_letters);

    free(small_letters);
    free(big_letters);

    return 0;

}


void targil_2(char* str, char** big, char** small)
{
    

    char*arrbig = (char*)malloc(sizeof(str));
    assert(arrbig);
    char*arrsmall = (char*)malloc(sizeof(str));
    assert(arrsmall);

    int count_small = 0;
    int count_big = 0;
    int i = 0;

    while (str[i] != '\0')
    {
        if (str[i] >= 'a' && str[i] <= 'z')
            arrsmall[count_small++] = str[i];
        if (str[i] >= 'A' && str[i] <= 'Z')
            arrbig[count_big++] = str[i];
        i++;

    }

    arrsmall[count_small] = '\0';
    arrbig[count_big] = '\0';

    *big = arrbig;
    *small = arrsmall;



}



void printArr(char* str)
{
    int i = 0;
    while (str[i] != '\0')
    {
        printf("%3c", str[i++]);
    }
    printf("\n");
}
c pointers runtime-error dynamic-memory-allocation allocation
1个回答
0
投票

“CRT detected that the application write to memory after end of heap buffer”表示CRT检测到检测到应用程序在堆缓冲区结束后写入内存。

也就是说,

the standard library                   something you allocated with malloc
vvv                                                            vvvvvvvvvvv
CRT detected that the application wrote to memory after end of heap buffer
                  ^^^^^^^^^^^^^^^
                     your code

标准库注意到你的代码在你用

malloc
分配的东西结束后写入内存。

我可以立即看到问题:在这一行

char*arrbig = (char*)malloc(sizeof(str));

str
是一个指针,所以
sizeof(str)
是 4。您的程序分配 4 个字节,然后写入 8.

为什么只在调用

free
时才弹出错误?因为那是 CRT 检查你是否做了蠢事的时候。你的程序在不调用
free
时仍然在做愚蠢的事情,只是CRT没有注意到。

固定程序分配的字节数。

© www.soinside.com 2019 - 2024. All rights reserved.