简体   繁体   English

malloc,memset和免费正确使用

[英]malloc, memset and free correct usage

I've a problem with the use of malloc, memset and free, which doesn't work as expected. 我在使用malloc,memset和free时遇到问题,该问题无法按预期工作。 The problems is with the latest function printf, instead of printing "test", it prints some weird characters and then test, something like "@#°test". 问题在于最新的函数printf,而不是打印“ test”,它先打印一些奇怪的字符然后进行测试,例如“ @#°test”。 Can you expalin me why? 你能解释我为什么吗? I've noticed that everything works fine if I do a memset after the second malloc. 我注意到,如果我在第二个malloc之后执行memset,则一切正常。 Also, I really don't get why everything works fine if I don't call the function "function()", even without a memset 另外,我真的不明白为什么即使不使用memset也不调用函数“ function()”也能正常工作的原因

Here's my code: 这是我的代码:

#define size 10
void function(){
   ...
   ...other code...
   ...
   char *b=malloc(size);
   read(file_ds,b,size); //file_ds stands for file descriptor, correctly opened with open function.
   memset(b,0,size);
   free(b);
}

void main(){
   ...
   ...other code...
   ...
   function(); //If I don't call this, everything works fine, even without a memset
   char *c=malloc(size);
   strcat(c,"test");
   printf("%s",c);
}

strcat expects that the address you give it points to a valid string, and it will attempt to find the end of that string by looking for a zero byte. strcat期望您提供的地址指向有效的字符串,并且它将尝试通过查找零字节来查找该字符串的结尾。 Your pointer, however, points into uninitialized memory, and it is undefined behaviour to attempt to read it. 但是,您的指针指向未初始化的内存,尝试读取它是未定义的行为。

Changing malloc to calloc provides you with initialized memory. malloc更改为calloc可为您提供初始化的内存。 However, that may be overkill, since it's enough to have an initialized initial segment , which you can achieve like thisL 但是,这可能是过大的,因为拥有一个初始化的初始段就足够了,您可以像这样实现L

char *c = malloc(size);
c[0] = '\0';

strcat(c, "test");  // OK

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

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