c pointer, how to free it/them into a function

前端 未结 5 1867
小鲜肉
小鲜肉 2020-12-17 07:02

This is my code:

#include 
#include 
#include 

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

in         


        
5条回答
  •  隐瞒了意图╮
    2020-12-17 07:32

    Yeah, you don't have to free anything if this is the whole program.

    The whole reason to free memory is so it can be reused somewhere later in the program. Even if your program went on from this point, you've only allocated a small number of bytes. It's OK to allocate them and keep them forever.

    In fact, you don't even have to do the arithmetic you're doing there to carve out exact-sized mallocs, you could say Oh, usernames and hostnames are never more than like 30 chars, just to be sure I'll allocate 256 char blocks. Oh wait your max is 8 chars, whatever. Or even just make a global buffer 256 chars or 8 chars long. Then make sure your strncpy()s never go past len_max or else you're risking a buffer overflow hack.

    meanwhile that getinfo() looks painful. Try something like fgets(mybuffer, len_max, stdin).

    Last I checked, the executable doesn't even bother to 'free' all unfreed blocks at the end, it just walks away. The VM system returns all the used memory (including the stack and program code) to the OS, and the process vaporizes and it's over. The malloc()ed blocks are just a pattern of bytes on that memory, and it's all forgotten.

提交回复
热议问题