Garbage Values
定义变量之后需要进行初始化,C语言不会自动初始化,会随机赋值,这样可能会产生 垃圾值garbage values。
int main(void)
{
int *x;
int *y;
x = malloc(sizeof(int));
*x = 42;
*y = 13;
y = x;
*y = 13;
}
其中没有为x寻求一个内存,所以不太好,可能会有垃圾值出现。修改如下:
Swap
void swap(int a, int b);
int main(void)
{
int x = 1;
int y = 2;
printf("x is %i, y is %i\n", x, y);
swap(x, y);
printf("x is %i, y is %i\n", x, y);
}
void swap(int a, int b)
{
int tem = a;
int b = a;
int a = tem;
}
终端输出:
x is 1, y is 2
x is 1, y is 2
修改如下:
void swap(int *a, int *b);
int main(void)
{
int x = 1;
int y = 2;
printf("x is %i, y is %i\n", x, y);
swap(&x, &y);
printf("x is %i, y is %i\n", x, y);
}
void swap(int *a, int *b)
{
int tem = *a;
int *b = *a;
int *a = tem;
}
终端输出:
x is 1, y is 2
x is 2, y is 1
heap over
stack over
buffer overflow
Scanf
下面为C语言中不使用get_int();的替代写法。很复杂,所以需要辅助轮。
#include <stdio.h>
int main(void)
{
int x;
print("x:");
scanf("%i", &x);
printf("x: %i\n", x);
}
下面为字符串的输入语法。需要给变量初始值,等于申请一个内存,避免溢出;输入字符串也不可以超出定义的内存,否则会发生溢出。
#include <stdio.h>
int main(void)
{
char *s[4];
print("s:");
scanf("%s", &s);
printf("s: %s\n", s);
}