C Memory Management

前端 未结 12 1180
旧时难觅i
旧时难觅i 2020-11-30 16:54

I\'ve always heard that in C you have to really watch how you manage memory. And I\'m still beginning to learn C, but thus far, I have not had to do any memory managing rela

12条回答
  •  情深已故
    2020-11-30 17:22

    Here's an example. Suppose you have a strdup() function that duplicates a string:

    char *strdup(char *src)
    {
        char * dest;
        dest = malloc(strlen(src) + 1);
        if (dest == NULL)
            abort();
        strcpy(dest, src);
        return dest;
    }
    

    And you call it like this:

    main()
    {
        char *s;
        s = strdup("hello");
        printf("%s\n", s);
        s = strdup("world");
        printf("%s\n", s);
    }
    

    You can see that the program works, but you have allocated memory (via malloc) without freeing it up. You have lost your pointer to the first memory block when you called strdup the second time.

    This is no big deal for this small amount of memory, but consider the case:

    for (i = 0; i < 1000000000; ++i)  /* billion times */
        s = strdup("hello world");    /* 11 bytes */
    

    You have now used up 11 gig of memory (possibly more, depending on your memory manager) and if you have not crashed your process is probably running pretty slowly.

    To fix, you need to call free() for everything that is obtained with malloc() after you finish using it:

    s = strdup("hello");
    free(s);  /* now not leaking memory! */
    s = strdup("world");
    ...
    

    Hope this example helps!

提交回复
热议问题