C Memory Management

前端 未结 12 1230
旧时难觅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:35

    There are some great answers here about how to allocate and free memory, and in my opinion the more challenging side of using C is ensuring that the only memory you use is memory you've allocated - if this isn't done correctly what you end up with is the cousin of this site - a buffer overflow - and you may be overwriting memory that's being used by another application, with very unpredictable results.

    An example:

    int main() {
        char* myString = (char*)malloc(5*sizeof(char));
        myString = "abcd";
    }
    

    At this point you've allocated 5 bytes for myString and filled it with "abcd\0" (strings end in a null - \0). If your string allocation was

    myString = "abcde";
    

    You would be assigning "abcde" in the 5 bytes you've had allocated to your program, and the trailing null character would be put at the end of this - a part of memory that hasn't been allocated for your use and could be free, but could equally be being used by another application - This is the critical part of memory management, where a mistake will have unpredictable (and sometimes unrepeatable) consequences.

提交回复
热议问题