C指针,指向,如何将它/他们自由进入功能 [英] c pointer, how to free it/them into a function

查看:149
本文介绍了C指针,指向,如何将它/他们自由进入功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的code:

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

void getinfo(unsigned int a, unsigned int b, char **pStr);

int main(){
    unsigned int len_max = 8;
    unsigned int current_size = 0;
    current_size = len_max;
    char *host, *user;
    char *pStr = malloc(len_max);
    if(pStr == NULL){
        perror("\nMemory allocation\n");
        return EXIT_FAILURE;
    }
    printf("Inserisci hostname: ");
    getinfo(len_max, current_size, &pStr);
    if((host=malloc(strlen(pStr)+1 * sizeof(char))) == NULL) abort();
    strncpy(host, pStr, strlen(pStr)+1);
    printf("Inserisci username: ");
    getinfo(len_max, current_size, &pStr);
    if((user=malloc(strlen(pStr)+1 * sizeof(char))) == NULL) abort();
    strncpy(user, pStr, strlen(pStr)+1);
    printf("\nHostname: %s\nUsername: %s\n", host, user);
    free(pStr);
    free(host);
    free(user);
    return EXIT_SUCCESS;
}

void getinfo(unsigned int a, unsigned int b, char **pStr){
    unsigned int i = 0;
    int c = EOF;
    while((c = getchar()) != '\n'){
        (*pStr)[i++] = (char)c;
        if(i == b){
            b = i+a;
            if((*pStr = realloc(*pStr, b)) == NULL){
                perror("\nMemory allocation error\n");
                exit(EXIT_FAILURE);
            }
        }
    }
    (*pStr)[i]='\0';
}

问题是,如果失败的realloc我必须退出(因为我无法分配内存)。但是,退出之前有释放所有使用的指针。照片的问题是,如果函数失败在第一时间里只有1有被释放(PSTR)指针。结果但是,如果失败,第二次有两个指针有被释放(PSTR&安培;用户)。结果
我该如何解决呢?

The problem is that if realloc fails i have to exit (because i cannot allocate memory). But before exit there's to free all the used pointers.
The problem is that if the function fails the first time there's only 1 pointer that have to be freed (pStr).
But if it fails the second time there's 2 pointers that have to be freed (pstr & user).
How can i fix it?

推荐答案

正如前面提到的,如果你要退出,那么所有实用的现代O / S将退出之前释放分配的内存。它并不总是这样; AmigaDOS,IIRC,早期版本没有回收分配的内存会自动重新启动前

As already noted, if you are going to exit, then all practical modern O/S will release the allocated memory before exit. It was not always thus; early versions of AmigaDOS, IIRC, did not reclaim allocated memory automatically until reboot.

这是一个简单的例子。还有更复杂的情况,比如你正在分析文件到内存和579 内存分配失败,而你想释放previous 578内存分配,使用户可以再试一次。

This is a simple case. There are more complex cases, such as you are parsing a file into memory and the 579th memory allocation fails, and you'd like to release the previous 578 memory allocations so that the user can try again.

在这种情况下,你必须保持每一个内存分配的记录是相关的(这本身可能需要一些内存分配&MDASH;但如果你解析一个文件,你可能有一个主结构,其中包含完整的说明),然后释放所有分配的数据。

In such cases, you have to keep a record of each memory allocation that is relevant (which may itself require some memory allocation — though if you're parsing a file, you probably have a master structure which contains the complete description) and then release all the allocated data.

在你的榜样,如果这不是一个的main()功能,如果你没有在内存分配错误中止,那么你就需要确保三个分配指针被释放从函数退出。该标准的技巧包括:

In your example, if this was not a main() function and if you did not abort on memory allocation error, then you would need to ensure that the three allocated pointers are released on exit from the function. The standard tricks for that include:


  1. 初始化指针为0,使他们能够可靠地释放:

  1. Initialize the pointers to 0 so they can be freed reliably:

char *host = 0;
char *user = 0;


  • 在使用的realloc(),不分配的结果作为第一个参数传递的前pression:

  • When using realloc(), do not assign the result to the expression passed as the first parameter:

    不这样做:

    ptr = realloc(ptr, newsize);
    

    如果(当) PTR 是分配的内存仅作参考,再分配失败了,你刚刚泄漏内存;有没有办法来释放仍被分配给你的内存。

    If (when) ptr is the only reference to the allocated memory and the reallocation fails, you've just leaked memory; there is no way to release the memory that is still allocated to you.

    使用:

    void *newptr = realloc(oldptr, newsize);
    if (newptr == 0)
        ...recover from memory allocation failure
    oldptr = newptr;
    

    在简单版本的问题在于,你刚刚扔掉已分配内存的唯一参考。 (请注意,code落入危险/泄露模式)。

    The trouble with the simpler version is that you've just thrown away the only reference to the allocated memory. (Note that your code falls into the dangerous/leaking pattern).

    请注意该pretty得多,其获取资源返回之前必须要么释放所获取的资源,或者使资源提供给该程序的其他部分,使得另一部分可以释放资源时,它的每个函数用它做。

    Note that pretty much every function that acquires resources must either release the acquired resource before returning, or make the resource available to some other part of the program so that the other part can release the resource when it is done with it.

    在'使可用的操作可能会返回获取资源(认为它是记忆,但它可能是一个文件描述符,目录流,或者大量的其他分配的资源)调用函数,或其存储在传递给当前函数的结构,或将其复制到全局或(文件)静态变量,甚至在(功能)积攒它的静态变量,因此如果函数被再次调用,它有一些资源可用入境。

    The 'make available' operation might be returning the acquired resource (think of it as memory, but it could be a file descriptor, directory stream, or any of a large number of other allocated resources) to the calling function, or storing it in a structure that was passed to the current function, or copying it to a global or (file) static variable, or even stashing it in a (function) static variable so if the function is called again, it has some resource available on entry.

    这篇关于C指针,指向,如何将它/他们自由进入功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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