2011年5月1日 星期日

[C/C++] Addition of data-structure sentinel

The accidental addition of a data-structure sentinel can cause serious programming logic problems.

例子:
char *foo;
foo = malloc(sizeof(char)*4);
foo[0] = 'a';
foo[1] = 'a';
foo[2] = 0;
foo[3] = 'c';
printf("%c %c %c %c %c \n",foo[0],foo[1],foo[2],foo[3]);
printf("%s\n",foo);

解決方案就是 encapsulating the user from interacting with data sentinels, 例如使用 std::string class.

沒有留言:

張貼留言