我最近尝试了一些C编程,偶然发现了以下问题.我正在使用带有MinGW 32位的NetBeans 7.4 64 IDE.这是一个简短的示例代码,它突出了我的问题:
int main(void) {
unsigned short int temp;
char *pointer;
pointer = malloc(12 * sizeof(char));
printf("The pointers value is %d \n", (int)pointer);
printf("Type a short string:\n");
gets(pointer);
printf("The pointers value is %d \n", (int)pointer);
printf("Type an int: \n");
//This line changes the char pointer to an apparently random value
scanf("%d", &temp);
//Segmentation fault upon this point
printf("The pointers value is %d \n", (int)pointer);
//And here as well
free(pointer);
return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
直到scanf一切都很好.读取的字符串被写入指向的内存空间指针.但是,在处理了scanf后,指针的值会发生变化,因此指针指向任何空间.所以不仅我的字符串丢失了,而且在尝试访问/释放不属于我的程序的内存时也会出现分段错误.
价值变化显然是随机的.每次我调试这个程序时,指针都会变为另一个值.
我已经推断出unsigned short int是错误的,或者说是我的scanf中错误的格式说明符(%d而不是%hu).如果我将unsigned …