简体   繁体   English

这会泄漏内存吗?

[英]Will this leak memory?

I made a small function to catenate strings and return the combined string. 我做了一个小函数来catenate字符串并返回组合字符串。 However since I assign memory to a third variable in the function, will the memory be freed when the function finishes or will it stay there, requiring me to free it later? 但是,由于我将内存分配给函数中的第三个变量,当函数完成时是否会释放内存,或者它会留在那里,要求我以后释放它? and if I need to free it, what's the most stylish solution to do it? 如果我需要释放它,那么最时尚的解决方案是什么?

Here's the test code. 这是测试代码。 It works, but I can't tell if that memory is freed or not with my tools. 它有效,但我无法判断是否使用我的工具释放了内存。

#include <stdio.h>
#include <math.h>
#include <string.h>

char * StrCat(const char *st1, const char *st2){
    char *string = calloc((strlen(st1) + strlen(st2) + 1), sizeof(char));
    strcat(string, st1);
    strcat(string, st2);
    return string;
}

int main(){
    printf("String: %s\n", StrCat("HELLO ", "WORLD"));
    return 0;
}

Yes you need to free it. 是的,你需要释放它。

Probably something like: 可能是这样的:

int main(){
    char *s = StrCat("HELLO ", "WORLD");
    printf("String: %s\n", s);
    free(s);
    return 0;
}

Since the applications ends right after printf, there's really no need to free it, since the application will do that for you when it dies. 由于应用程序在printf之后立即结束,因此实际上不需要释放它,因为应用程序会在它死后为您执行此操作。 But yes, it's always good practice to free it. 但是,是的,释放它总是好习惯。

Yes, you have to free it. 是的,你必须释放它。 Try valgrind to detect the leak. 尝试valgrind来检测泄漏。

Yes. 是。 If you call calloc, malloc, new, etc. a call to a function that frees the memory must also be made. 如果调用calloc,malloc,new等,则还必须调用释放内存的函数。

memory leaks and free memory this is tricky problems. 内存泄漏和空闲内存这是棘手的问题。 may be worth trying the debugger? 可能值得尝试调试器? I use deleaker for solving such problems. 我使用deleaker来解决这些问题。

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

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