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覆蓋)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM