简体   繁体   English

如何在没有内存泄漏的情况下正确分配 char[]

[英]How to malloc a char[] properly without memory leaks

How do I fix this line to work with my code.如何修复此行以使用我的代码。 I know in C99 variable-length arrays are allowed, but I need to use malloc to fix this line.我知道在 C99 中允许使用可变长度数组,但我需要使用 malloc 来修复这一行。 How would I go about doing that.我将如何去做。 char stack[strlen(input)]; (I am not using C99, by the way) (顺便说一下,我没有使用 C99)

Declare stack as pointer and use malloc .stack声明为指针并使用malloc

char *stack = malloc(strlen(input));

Don't forget to free the memory.不要忘记free内存。

Allow me to add that it's recommended to always check the value of a pointer you just allocated with malloc.请允许我补充一点,建议始终检查您刚刚使用 malloc 分配的指针的值。

You can do it this way :你可以这样做:

char *stack = malloc(strlen(input));
if (stack == NULL) {
  return -1;
}

You can modify the return -1;可以修改return -1; with whatever you want depending where you are using this part of code.根据您使用这部分代码的位置,随心所欲。 -1 being what some people usually return when an error occurs. -1 是某些人在发生错误时通常返回的内容。

Why do that?为什么要这样做?

The malloc() function can fail allocating memory space in case RAM is full for example.例如,在 RAM 已满的情况下, malloc()函数可能无法分配内存空间。 This doesn't happen often but it has to be catched for code correctness.这并不经常发生,但为了代码的正确性,必须抓住它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM