简体   繁体   English

将scanf用于char * c时发生内存泄漏

[英]memory leakage while using scanf for char* c

can you please tell me what is wrong with the following input process? 您能告诉我以下输入过程有什么问题吗?

the input should be a string length and then the string itself. 输入应该是字符串长度,然后是字符串本身。

something like "5 vlady" 像“ 5 vlady”

It works just fine, but valgrind (memory leakage tool) tell the following exception: 它工作正常,但是valgrind(内存泄漏工具)告诉以下异常:

Address 0x51ef184 is 0 bytes after a block of size 4 alloc'd 在分配大小为4的块后,地址0x51ef184为0字节

Her's the code: 她的代码是:

unsigned int n;
char* string;

printf("Enter your string:\n");
scanf("%d", &n);
string = (char*)calloc((n),sizeof(char));
scanf("%s", string);

Thanks! 谢谢!

The posted code is writing one byte beyond the allocated memory as scanf("%s") appends a terminating null character. 由于scanf("%s")追加了终止的空字符,因此发布的代码正在超出分配的内存写入一个字节。 Description for format specifier s from section 7.19.6.2 fscanf function of the C99 standard: C99标准的7.19.6.2fscanf函数的格式说明符s说明:

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically . 如果没有l长度修饰符,则相应的参数应为指向字符数组初始元素的指针,该元素的大小应足以接受该序列和一个终止的空字符,该字符将自动添加

Therefore allocate n + 1 bytes. 因此分配n + 1个字节。

Other: 其他:

  • always check the result of IO operations to ensure variables have been assigned a value: 始终检查IO操作的结果,以确保已为变量分配值:

     /* 'scanf()' returns number of assignments made. Use '%u' for reading an unsigned int. */ if (scanf("%u", &n) == 1) { } 
  • prevent buffer overrun by limiting the number of bytes consumed by scanf() by using the %Ns format specifier, where N is the number characters to read. 通过使用%Ns格式说明符限制scanf()消耗的字节数来防止缓冲区溢出,其中N是要读取的数字字符。 In this case, the format specifier would need constructed, using sprintf() for example. 在这种情况下,将需要使用sprintf()构造格式说明符。 Another option is to use fgets() but this does not stop reading when white space is encountered. 另一个选择是使用fgets()但是遇到空白时它不会停止读取。

  • Do I cast the result of malloc? 我要转换malloc的结果吗?

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

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