02 WIndows编程——危险的sizeof

C语言中,对 sizeof() 的处理都是在编译阶段进行。

#include<Windows.h>
#include<stdio.h>

int MessageBoxPrint(char *szFormat, ...);
int fun(char ch[]);

int WinMain(HINSTANCE hInst, HINSTANCE tmp, LPSTR strCmd, int nShow)
{
    char str[1024];
    MessageBoxPrint("%p", hInst);
    MessageBoxPrint("ch=%d", fun(str));
    return 0;
}

int MessageBoxPrint(char *szFormat, ...)
{
    char buf[1024];
    va_list va;
    va_start(va, szFormat);
    vsnprintf(buf, sizeof(buf), szFormat, va);
    va_end(va);
    return MessageBox(NULL,buf,"printf",MB_OK);
}

int fun(char ch[])
{
    return sizeof(ch);
}
View Code

sizeof在fun函数种计算的是指针ch的长度,32位OS下恒为4

sizeof计算字符串含要看在什么位置,写完代码时很难预估风险,最好使用strlen

修改如下

#include<Windows.h>
#include<stdio.h>

int MessageBoxPrint(char *szFormat, ...);
int fun(char ch[]);

int WinMain(HINSTANCE hInst, HINSTANCE tmp, LPSTR strCmd, int nShow)
{
    char str[1024];
    MessageBoxPrint("%p", hInst);
    MessageBoxPrint("ch=%d", fun(str));
    return 0;
}

int MessageBoxPrint(char *szFormat, ...)
{
    char buf[1024];
    va_list va;
    va_start(va, szFormat);
    vsnprintf(buf, sizeof(buf), szFormat, va);
    va_end(va);
    return MessageBox(NULL,buf,"printf",MB_OK);
}

int fun(char ch[])
{
    return strlen(ch);
}
View Code

这时还有个问题,由于WinMain里面str没有初始化,strlen计算长度的时候,长度是未知的。因为他要一直找到\0在完事,所以strlen的时候长度可能大于1024,可能等于1024,也可能小于1024。

猜你喜欢

转载自www.cnblogs.com/kelamoyujuzhen/p/9298249.html
02
今日推荐