码迷,mamicode.com
首页 > 其他好文 > 详细

sizeof对函数入参使用不准

时间:2014-05-29 16:40:15      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

 

被调用函数内部,无法知道入参的字符数组的可用内存长度
所以函数字符指针作为入参时,一定要加一个 此指针指向的内存空间长度入参int nSize

错误的写法:

bubuko.com,布布扣
 1 #include "stdafx.h"
 2 #include <string.h>
 3 #include <stdarg.h>
 4 
 5 // 返回非0表达式验证不通过,不用调用子系统功能号
 6 int getFilters(char * pszInput, char *pszFuncid)
 7 {
 8     char sztmp[64]={0,};
 9     char szFilters[256]={0,};
10     char szFilter[256]={0,};
11     char szFilterName[64]={0,};
12     char szFilterVal[256]={0,};
13     char sztmpVal[512]={0,};
14 
15     // 被调用函数内部,无法知道字符数组的可用内存长度
16    //所以函数形参字符指针,用char * pszInput,int nSize
17     // int a = sizeof(pszInput);  //sizeof不准 a=4
18     // int b = sizeof(*pszInput);  //sizeof不准 b=1
19     // int c = strlen(pszInput);  //strlen测量字符串的字符个数 c=18
20     strncpy(sztmpVal, pszInput, sizeof(pszInput)); // sztmpVal = "2610"
21 
22    //...
23     return 0;
24 }
25 
26 
27 
28 int _tmain(int argc, _TCHAR* argv[])
29 {
30     char szFuncid[64]={0,};
31     char szOtcCfg[512]={0,};
32 
33     sprintf(szOtcCfg,"26100012[EMAIL=wx]");
34 
35     int b = sizeof(szOtcCfg);  //  b=512
36     getFilters(szOtcCfg, szFuncid);
37 
38     getchar();
39 
40     return 0;
41 }
bubuko.com,布布扣

 正确的写法:

bubuko.com,布布扣
 1 // test.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <string.h>
 6 #include <stdarg.h>
 7 
 8 // 返回非0表达式验证不通过,不用调用子系统功能号
 9 int getFilters(char * pszInput,int nSize, char *pszFuncid)
10 {
11     char sztmp[64]={0,};
12     char szFilters[256]={0,};
13     char szFilter[256]={0,};
14     char szFilterName[64]={0,};
15     char szFilterVal[256]={0,};
16     char sztmpVal[512]={0,};
17 
18     // 被调用函数内部,无法知道字符数组的可用内存长度, 所以函数形参字符指针,要用char * pszInput,int nSize
19     // int a = sizeof(pszInput);  //sizeof不准 a=4
20     // int b = sizeof(*pszInput);  //sizeof不准 b=1
21     // int c = strlen(pszInput);  //strlen测量字符串的字符个数 c=18
22     strncpy(sztmpVal, pszInput, nSize);  // sztmpVal=26100012[EMAIL=wx]
23 
24    // ...
25 
26     return 0;
27 }
28 
29 
30 
31 int _tmain(int argc, _TCHAR* argv[])
32 {
33     char szFuncid[64]={0,};
34     char szOtcCfg[512]={0,};
35 
36     sprintf(szOtcCfg,"26100012[EMAIL=wx]");
37 
38     int b = sizeof(szOtcCfg);
39     getFilters(szOtcCfg, sizeof(szOtcCfg), szFuncid);
40 
41     getchar();
42 
43     return 0;
44 }
bubuko.com,布布扣

 

sizeof对函数入参使用不准,布布扣,bubuko.com

sizeof对函数入参使用不准

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/trmark/p/3758589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!