C语言常见数据类型在32位及64位机器上的使用

概述

C语言有一些非常基本的数据类型,正是这些基本类型让我们可以延伸了无限的用户自定义类型,本文主要
介绍了int, size_t, time_t, long, long long int 等基本数据类型在Linux32Linux64 的使用情况。

示例代码:
#include <stdio.h>
#include <stdlib.h>

static void get_length(size_t *size)
{
	if (size)
		*size = 100;
}


static void test(void)
{
	char *buf = "hello world";
	int n;
	printf("buf: %s\n", buf);
	get_length((size_t*) &n);
	printf("buf: %s, n: %d\n", buf, n);
}


int main(int argc, char *argv[])
{
	test();
	return (0);
}
Linux32运行结果
buf: hello world
buf: hello world, n: 100
Linux64运行结果
buf: hello world
buf: (null), n: 100

一些基本类型在32位及64位机上的大小差异

机器架构 int long size_t time_t long long int
32 4字节 4字节 4字节 4字节 8字节
64 4字节 8字节 8字节 8字节 8字节

原因分析

应为int和size_t在32位机器下都是4字节大小的,所以不会出现问题。
而64位机器上int是4字节的size_t是8字节的,所以调用get_length函数时(get_length((size_t*) &n);),
就覆盖了传入的int *之前的4字节地址空间(即char *buf 的地址空间被0x00覆盖)。

posted @ 2017-03-05 09:14  历史漫步  阅读(2946)  评论(0)    收藏  举报