没有Null指针检索的无效字符串拷贝(导致日志文件 - WinCC_Sys_xx.LOG中的“ExecuteError in Action” ) 当动作在执行并且图像被取消选定(目标未发现)时此条目出现在WinCC_Sys.Log中- 错误:
- char sign[5];
- strcpy(sign,GetText(lpszPictureName,lpszObjectName));
- if (0==strcmp(sign,"+"))
- {
- SetText(lpszPictureName,lpszObjectName,"-");
- SetVisible(lpszPictureName,"B5",TRUE);
- }
- else
- {
- SetText(lpszPictureName,lpszObjectName,"+");
- SetVisible(lpszPictureName,"B5",FALSE);
- }
为了避免无意的复制太多的字符到“sign” (例如在后来作改动时) ,并为了避免当取消选定图像时由于“strcpy()”导致的异常,在“strncpy()”复制到Null-指针之前应该使用和检查“strncpy()” 。
- 正确:
- char sign[5], *myPointer;
- myPointer = GetText(lpszPictureName,lpszObjectName);
- if(myPointer != NULL)
- {
- strncpy(sign, myPointer, 4);
- if (0==strcmp(sign,"+"))
- {
- SetText(lpszPictureName,lpszObjectName,"-");
- SetVisible(lpszPictureName,"B5",TRUE);
- }
- else
- {
- SetText(lpszPictureName,lpszObjectName,"+");
- SetVisible(lpszPictureName,"B5",FALSE);
- }
- }
- else
- {
- printf("Error in GetText() !\r\n");
- }
警告: 函数strcpy()将“Source”指针所指向的包含末尾字符'\0’的字符串复制到“Target”指针指向的位置。字符串不能 重叠,并且目标必须足够大 (源字符串长度 + 1,因为有'\0’)。函数strncpy()除了仅复制起始的n个字节外其余与函数strcpy()相同。如果起始的n个字节中没有'\0’,结果将不是以'\0’结束。这将导致未定义的系统状态。
用strcat函数来连接字符串。
假设有四个变量tag1,tag2,tag3,tag4都是8位文本字符变量。把tag1~tag3连接起来显示在tag4中。测试:先建立这四个变量,然后在wincc的画面中建立四个输入输出域,分别连接tag1~tag4,建立一个按钮,在按钮的c动作中:
char buffer[256]="";
strcat(buffer,GetTagChar("tag1"));
strcat(buffer,GetTagChar("tag2"));
strcat(buffer,GetTagChar("tag3"));
SetTagChar("tag4",buffer);