简体   繁体   English

我无法释放 memory

[英]I can't free the memory

I'm in my 1st year of faculty and I have this homework:我在教职的第一年,我有这个作业:

Write a program that reads n arrays of characters and concatenates them into another dynamically allocated array.编写一个程序,读取 n 个 arrays 字符并将它们连接到另一个动态分配的数组中。 Repeat the operation as many times as the user desires.根据用户的需要重复该操作多次。

After each displaying of the result, the allocated memory is freed.每次显示结果后,分配的 memory 被释放。

And that is what I did:这就是我所做的:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>

int main()
{
    char** p, * v;
    int n, m;
    printf("\n\t enter the number of the arrays : \t");
    scanf("%d", &n);
    printf("\n\t enter the maximum lenght of the arrays :");
    scanf("%d", &m);
    p = (char**)malloc(sizeof(char) * n);

    for (int i{}; i < n; i++)
        p[i] = (char*)malloc(sizeof(char) * m);

    char t = 'Y';
    while (t == 'Y')
    {
        size_t z = 0;
        printf("\n\t enter your arrays :");
        for (int i{}; i < n; i++) {
            scanf("%s", p[i]);
            z += strlen(p[i]);
        }
        v=(char* )malloc(z * sizeof(char));
        for (int i{}; i < n; i++)
            if (i == 0)
                strcpy(v, p[i]);
            else
                strcat(v, p[i]);
        if (v) {
            puts(v);
            free(v);
        }

        if (p)
            for (int i{}; i < n; i++)
                free(p[i]);

        printf("\n\t wanna continue ? (Y/N)");
        scanf("%d", &t);
    }
}

When I want to free the memory to use again, I get a "head corruption error" from the debugger.当我想释放 memory 以再次使用时,我从调试器中收到“磁头损坏错误”。

Any idea why?知道为什么吗?

Allocation size mistake分配大小错误

Code allocated the wrong size.代码分配了错误的大小。
Cast not needed either.也不需要演员。

char** p; 
...
p = (char**)malloc(sizeof(char) * n);  // Bad

Size to the tpye of the referenced object.大小为引用的 object 的类型。

p = malloc(sizeof *p * n);  // Good

Robust code would also check for errors.健壮的代码也会检查错误。

if (scanf("%d", &n) != 1 || n < 0) {
  fprintf(stderr, "No numeric input or negative count\n");
  // Perhaps exit here.
}

p = malloc(sizeof *p * n);
if (p == NULL && n > 0) {
  fprintf(stderr, "Allocation failed\n);
  // Perhaps exit here.
}

As an addition to the answer you need to change in the program properties option which selects what is the language C/C++作为答案的补充,您需要更改程序属性选项,该选项选择什么是语言 C/C++

在此处输入图像描述

Update: I did it: That's the final code :更新:我做到了:这是最终代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include <stdbool.h>
bool ver(bool);

int main()
{
    int n, m;
    char** myarray;
    bool y = true;


    while (y == true) {
        printf("enter the number of arrays : ");
        scanf("%d", &n);
        myarray = malloc(n * sizeof(char*));
        if (myarray == NULL && n > 0) {
            fprintf(stderr, "Allocation failed\n");
            exit(1);
        }
        printf("enter the  maximum size of the  arrays : ");
        scanf("%d", &m);
        for (int i = { 0 }; i < n; i++)
            myarray[i] = malloc(m * sizeof(char));


        printf("\n\t enter your stings : \n");
        size_t x = 0;
        for (int i = 0; i < n; i++)
        {
            if (myarray[i])
                scanf("%s", myarray[i]);
            x += sizeof(myarray[i]);
        }
        char* v;
        v = malloc(x * sizeof(char));
        if (v == NULL && x > 0) {
            fprintf(stderr, "Allocation failed\n");
            exit(1);
        }
        strcpy(v, myarray[0]);
        for (int i = 1; i < n; i++)
            strcat(v, myarray[i]);
        puts(v);
        free(v);
        for (int i = 0; i < n; i++)
            free(myarray[i]);
        free(myarray);
        y = ver(y);



    }
}
bool ver(bool r) {
    char var;
    printf("\n\twanna continue ? (Y/N)\n");
    scanf(" %c", &var); 
    while(var != 'Y' && var != 'N')
    {
        printf("\n\tInvalid input  !\n wanna continue ?(Y/N).");
        scanf(" %c", &var);
    }

    if (var == 'N')
        r = false;
    else
        r= true;
    return r;
} 

I am still new to C, if you have any suggestion please tell.我对 C 还是新手,如果您有任何建议,请告诉。

I get warnings, maybe I forgot some checks (malloc/scanf).我收到警告,也许我忘记了一些检查(malloc/scanf)。

I hope I helped you even though I'm a beginner.我希望我能帮助你,即使我是初学者。

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<stdbool.h>

struct cstring {

    char* data;
    size_t size;

};

bool create_cstring(struct cstring* const object, const size_t size) {

    return (object->data = calloc(size, sizeof(char))) ?
        (object->size = size + 1U) :
        (object->size = 0U);

}

bool destroy_cstring(struct cstring* const object) {

    free(object->data);
    object->size = 0U;

}

struct cvector_string {

    struct cstring* data;
    size_t size;

};

bool create_cvector_string(struct cvector_string* const object, const size_t size) {

    return (object->data = calloc(size, sizeof(struct cstring))) ?
        (object->size = size) :
        (object->size =   0U) ;

}

void destroy_cvector_string(struct cvector_string* const object) {

    free(object->data);
    object->size = 0U;

}

int main()
{

    struct cvector_string cv = { NULL, 0U };

    // Allocations 
    {

        // Allocate n arrays of chars
        {

            size_t cv_n = 0;

            printf("\n\t Enter the number of the arrays : \t"); 
            scanf("%zu", &cv_n);

            if (!create_cvector_string(&cv, cv_n)) {

                fprintf(stderr, "Error : Bad allocation\n");
                return 1;

            }

        }

        // Allocate arrays of n chars
        {

            size_t cv_m = 0;

            printf("\n\t Enter the maximum lenght of the arrays : \t");
            scanf("%zu", &cv_m);

            for (struct cstring* it = cv.data; it != cv.data + cv.size; ++it) {

                if (!create_cstring(it, cv_m)) {

                    fprintf(stderr, "Error : Bad allocation\n");
                    return 1;

                }

            }

        }

    }

    struct cstring r = { NULL, 0U };


    {

        char cont = '\0';

        do {

            /* Initialize arrays of chars, calculate the length of the resulting string
             * and create the resulting string */
            {

                size_t length_sum = 0;

                for (struct cstring* it = cv.data; it != cv.data + cv.size; ++it) {

                    scanf("%s", it->data);
                    length_sum += strlen(it->data);

                }

                if (!create_cstring(&r, length_sum)) {

                    fprintf(stderr, "Error : Bad allocation\n");
                    return 1;

                }

            }

            // Initialize and concatenate the resulting string
            {

                strcpy(r.data, cv.data[0].data); 
                // or using destination = strcpy(malloc, source), same for strcat

                for (struct cstring* it = cv.data + 1; it != cv.data + cv.size; ++it) strcat(r.data, it->data);

            }


            // Print and deallocate the resulting string

            puts(r.data);
            destroy_cstring(&r);

            // Prompt to continue

            printf("\n\t Wanna continue? (Y/N) ");
            scanf(" %c", &cont);

        } while (cont == 'Y');

    }

    // Deallocations 
    {

        // Deallocate all the arrays of chars
        for (struct cstring* it = cv.data; it != cv.data + cv.size; ++it) destroy_cstring(it);

        // Deallocate the array of arrays of chars
        destroy_cvector_string(&cv);

    }

}

Errors:错误:

  1. You're freeing the allocated memory for character arrays and then reading into that memory.您正在为字符 arrays 释放分配的 memory,然后读入该 memory。

Deallocating解除分配

 for (int i{}; i < n; i++)
                free(p[i]);

Using使用

 for (int i{}; i < n; i++) {
            scanf("%s", p[i]);
            z += strlen(p[i]);
        }
  1. You have to allocate memory for pointers, not allocate memory for characters.您必须为指针分配 memory,而不是为字符分配 memory。

     p = (char**)malloc(sizeof(char) * n);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM