现在在人们开始将它标记为dup之前,我已经阅读了以下所有内容,其中没有一个提供我正在寻找的答案:
C FAQ和上述问题的许多答案都引用了一个神秘的错误,即铸造malloc的返回值可以隐藏; 但是,它们都没有在实践中给出这种错误的具体例子.现在要注意我说的错误,而不是警告.
现在给出以下代码:
#include <string.h>
#include <stdio.h>
// #include <stdlib.h>
int main(int argc, char** argv) {
char * p = /*(char*)*/malloc(10);
strcpy(p, "hello");
printf("%s\n", p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用gcc 4.2编译上面的代码,有和没有强制转换都会给出相同的警告,并且程序正确执行并在两种情况下都提供相同的结果.
anon@anon:~/$ gcc -Wextra nostdlib_malloc.c -o nostdlib_malloc
nostdlib_malloc.c: In function ‘main’:
nostdlib_malloc.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’
anon@anon:~/$ ./nostdlib_malloc
hello
Run Code Online (Sandbox Code Playgroud)
那么,任何人都可以提供一个特定的代码示例,说明由于转换malloc返回值而可能发生的编译或运行时错误,或者这仅仅是一个城市传奇?
编辑我在这个问题上遇到了两个写得很好的论点:
我一直在做一个相当简单的程序,将一串字符(假设输入数字)转换为整数.
我改完之后,我注意到一些非常奇特的"错误",我不能回答大多是因我有限的知识如何,scanf(),gets()和fgets()职能的工作.(尽管我读过很多文学作品.)
所以没有写太多文本,这里是程序的代码:
#include <stdio.h>
#define MAX 100
int CharToInt(const char *);
int main()
{
char str[MAX];
printf(" Enter some numbers (no spaces): ");
gets(str);
// fgets(str, sizeof(str), stdin);
// scanf("%s", str);
printf(" Entered number is: %d\n", CharToInt(str));
return 0;
}
int CharToInt(const char *s)
{
int i, result, temp;
result = 0;
i = 0;
while(*(s+i) != '\0')
{
temp = *(s+i) & 15;
result = (temp + result) * 10;
i++;
} …Run Code Online (Sandbox Code Playgroud)