What happens if I use malloc twice on the same pointer (C)?

后端 未结 4 685
梦如初夏
梦如初夏 2020-12-30 01:31

Say for instance I created a pointer newPtr and I use malloc(some size) and then later I use malloc(some size) again with the same pointer. What happens? Am i then creating

4条回答
  •  太阳男子
    2020-12-30 02:08

    You're not actually using malloc on the same pointer. You're not giving the pointer to malloc at all. malloc always allocates new memory. So, the same thing happens as is the case with any variable assignment:

    int a;
    a = 14;
    a = 20;
    

    What happens to the 14? You can't access it anymore. In terms of malloc this means you no longer have a reference to the pointer it returned, so you'll have a memory leak.

    If you actually want to use "malloc with the same pointer", you might be interested in the realloc function:

    int *newPtr;
    newPtr = malloc(10 * sizeof(int));
    newPtr = realloc(newPtr, 10 * sizeof(int)); //*might leak memory*
    

    From that link: realloc "changes the size of the memory block pointed to by ptr. The function may move the memory block to a new location (whose address is returned by the function)."


    EDIT: Note that if realloc fails in the above, then it returns NULL, yet the memory pointed to by newPtr is not freed. Based on this answer, you could do this:

    void *emalloc(size_t amt){
        void *v = malloc(amt);  
        if(!v) {
            fprintf(stderr, "out of mem\n");
            exit(EXIT_FAILURE);
        }
        return v;
    }
    void *erealloc(void *oldPtr, size_t amt){
        void *v = realloc(oldPtr, amt);  
        if(!v) {
            fprintf(stderr, "out of mem\n");
            exit(EXIT_FAILURE);
        }
        return v;
    }
    

    and then:

    int *newPtr;
    newPtr = emalloc(10 * sizeof(int));
    newPtr = erealloc(newPtr, 10 * sizeof(int));
    

提交回复
热议问题