活跃农民
- 积分
- 467
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-5-3
- 最后登录
- 1970-1-1
|
本帖最后由 shijingshijing 于 2025-1-1 18:56 编辑 -baidu 1point3acres
看了一下第一题,主要考察的是函数内申请内存和参数传递?然后是字符串的内存结构?
第一个问题是传入的形式参数char *dest,应该改成char **dest,不能传字符串首字母的地址的值,而是应该传入字符串首字母的地址的指针,这样才能实现函数test_copy内部修改字符串的值的效果。相应的main函数中调用test_copy应该写成len = test_copy(src, &dest);
第二个问题是while(p) *q++ = *p++; 这里本意是想碰到字符串结尾的'\0'自动结束复制,所以按照题目本来出题的意思应该是while(*p);但是更稳妥的方法应该是while(p-src<len) *q++ = *p++; 很多基于字符串的攻击正是利用字符串溢出的方法来实现的,p-src<len强制复制完指定长度后就结束。
第三个问题是test_copy没有返回值,而main函数中调用的时候需要给出返回值,所以test_copy最后应该加上一句:return len;
还有一些细枝末节的小问题:
1,头函数应该include必须的库,不然printf,strcpy, malloc无法调用 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2,调用malloc的时候应该检查返回值,有可能存在无法分配内存的情况;. 1point 3 acres
修改后的完整代码如下,没有仔细想while循环,可能字符串结尾'\0'处理的还存在问题。
. 1point3acres
补充内容 (2025-01-01 18:54 +08:00):- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- /* the purpose of the function is to copy a string and return the copied length upon success */
- int test_copy(char *src, char **dest)
- {
- char *p, *q;
- int len = strlen(src);
- *dest = malloc(len);
- p = src;
- q = *dest;
- while(p-src<len) *q++ = *p++;
- *q = '\0';
- return len;. 1point 3acres
- }
- -baidu 1point3acres
- int main()
- {
- char src[100], *dest;
- int len;. 1point3acres
- strcpy(src, "hello world!");. Χ
- //len = strlen(src);
- //dest = malloc(len);
- len = test_copy(src, &dest);
- printf("the dest is %s len is %d\n", dest, len);
- return 0;
- }
复制代码 |
|