当函数返回其值时释放malloc
我有以下功能:当函数返回其值时释放malloc,c,malloc,C,Malloc,我有以下功能: char *lsl(){ chdir("/Users/some/directory"); FILE *fp; if ((fp = popen("ls -l", "r")) == NULL) { perror("popen failed"); return (char *)EXIT_FAILURE; } size_t str_size = 1024; char *stringts = malloc
char *lsl(){
chdir("/Users/some/directory");
FILE *fp;
if ((fp = popen("ls -l", "r")) == NULL) {
perror("popen failed");
return (char *)EXIT_FAILURE;
}
size_t str_size = 1024;
char *stringts = malloc(str_size);
if (!stringts) {
perror("stringts allocation failed");
return (char *)EXIT_FAILURE;
}
stringts[0] = '\0';
char buf[128];
size_t n;
while ((n = fread(buf, 1, sizeof(buf) - 1, fp)) > 0) {
buf[n] = '\0';
size_t capacity = str_size - strlen(stringts) - 1;
while (n > capacity) {
str_size *= 2;
stringts = realloc(stringts, str_size);
if (!stringts) {
perror("stringts realloation failed");
return (char *)EXIT_FAILURE;
}
capacity = str_size - strlen(stringts) - 1;
}
strcat(stringts, buf);
}
if (pclose(fp) != 0) {
perror("pclose failed");
return (char *)EXIT_FAILURE;
}
return stringts;
}
主要相关部分:
char *out=lsl();
if(send(new_socket, out, 200, 0)<0){. //sending the string to the client to print it there
printf("Error in send! %s\n", strerror(errno));
return -1;
}
char*out=lsl();
if(send(new_socket,out,200,0)如果要返回它,则不能释放()strings。以后必须在调用函数中释放()它
char *out=lsl();
int r = send(new_socket, out, 200, 0);
free(out);
if(r <0){. //sending the string to the client to print it there
printf("Error in send! %s\n", strerror(errno));
return -1;
}
char*out=lsl();
int r=发送(新的_插座,输出,200,0);
免费(外出);
if(r如果要返回它,则不能释放()stringts。以后必须在调用函数中释放()它
char *out=lsl();
int r = send(new_socket, out, 200, 0);
free(out);
if(r <0){. //sending the string to the client to print it there
printf("Error in send! %s\n", strerror(errno));
return -1;
}
char*out=lsl();
int r=发送(新的_插座,输出,200,0);
免费(外出);
如果(r)显然不能free
要返回的字符串。函数lsl
为字符串分配内存,初始化并返回该字符串。调用lsl
的函数使用该字符串,并在完成后对其调用free
。(但该函数可以自由地依次将字符串返回给调用方或将字符串存储在其他地方。接收字符串的人“拥有”该字符串,并负责释放它)。返回(char*)退出\u失败;
否。只需返回NULL
字符串=realloc即可(strings
如果realloc失败,则会导致内存泄漏。这就是为什么您使用带有realloc-void*tmp=realloc(string);if(!tmp){free(string);…}string=tmp;
的临时指针,那么我应该如何使用free()在使用后仍然返回它?
free
在main
中释放它…OT:在这里使用strcat
效率很低。谷歌“画师的算法”获取更多信息。我应该如何在main()
中释放它?因为我需要在send()之后将它发送给客户端
在客户端时不会被执行,而我只是从我制作的缓冲区中读取。@ayrebelcoding当然你可以在通过send
发送后释放它。一旦发送,它就被发送了。同样,如果你将某个东西写入文件,一旦写入,它就在文件中,你可以释放它。显然你不能释放你需要的字符串想要返回。您的函数lsl
为字符串分配内存,初始化并返回它。调用lsl
的函数使用该字符串,并在完成时对其调用free
。(但该函数可以自由地依次将字符串返回给调用方或将字符串存储在其他地方。接收字符串的人“拥有”该字符串,并负责释放它)。返回(char*)退出\u失败;
否。只需返回NULL
字符串=realloc即可(strings
如果realloc失败,则会导致内存泄漏。这就是为什么您使用带有realloc-void*tmp=realloc(string);if(!tmp){free(string);…}string=tmp;
的临时指针,那么我应该如何使用free()在使用后仍然返回它?
free
在main
中释放它…OT:在这里使用strcat
效率很低。谷歌“画师的算法”获取更多信息。我应该如何在main()
中释放它?因为我需要在send()之后将它发送给客户端
在客户端时不会被执行,我只是从我制作的缓冲区中读取数据。@ayrebelcoding当然你可以在通过send
发送后释放它。一旦发送,它就被发送了。如果你将某个内容写入文件,一旦写入,它就在文件中,你可以释放它。