免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1786 | 回复: 6
打印 上一主题 下一主题

高手帮忙解释一下三种指针传递方法的不同 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-07-30 15:55 |只看该作者 |倒序浏览
#include <stdio.h>
#include <string.h>

#define MAXLEN 1024

void LoopMove(char *pStr, int steps)
{
        int n = 0;
        char tmp[MAXLEN];

        n = strlen(pStr) - steps;
        strcpy(tmp, pStr+n);
        strcpy(tmp+steps, pStr);
        *(tmp+strlen(pStr)) = '\0';//把后面的部分进行截取
        memcpy(pStr, tmp, strlen(pStr));
        printf("%s\n", pStr);
}

int main()
{
        //方法一:输出会产生段错误
                char *test = "testhellloworld";
       
        //方法二:输出不会会产生段错误
                char test[] = "testhellloworld";

       
        //方法三:输出不会会产生段错误
        //char *test = (char *)malloc(sizeof(char)*MAXLEN);
        //strcpy(test, "testhellloworld");


        LoopMove(test, 3);
        printf("%s\n", test);
        return 0;
}

帮忙解释一下方法一产生段错误的原因

论坛徽章:
0
2 [报告]
发表于 2009-07-30 15:58 |只看该作者
因为第一个是不可写的,所以你不能对它进行写操作。

论坛徽章:
0
3 [报告]
发表于 2009-07-30 16:13 |只看该作者

回复 #1 scudong 的帖子

//方法一:   字符串常量(存储在常量存储区)
//方法二:   自动变量 (存储在栈中)
//方法三:   堆变量   (存储在堆中)

论坛徽章:
1
寅虎
日期:2014-11-30 21:25:54
4 [报告]
发表于 2009-07-30 16:16 |只看该作者
三个 test 在不同有内存段上 :
第一个  test 在 readonly data上
第二个  test 在 stack 上
第三个  test 在 heap 上

论坛徽章:
0
5 [报告]
发表于 2009-07-30 16:31 |只看该作者
如楼上两位所言,第一个存在 .text 段中,一般来说是只读的,不过还是有办法让它可写。
具体 man 2 mprotect

论坛徽章:
0
6 [报告]
发表于 2009-07-31 01:56 |只看该作者
原帖由 windaoo 于 2009-7-30 16:31 发表
如楼上两位所言,第一个存在 .text 段中,一般来说是只读的,不过还是有办法让它可写。
具体 man 2 mprotect

不是.text吧,应该是.rdate吧。

[ 本帖最后由 progliker 于 2009-7-31 02:02 编辑 ]

论坛徽章:
0
7 [报告]
发表于 2009-07-31 08:13 |只看该作者
2.13.4/1 in the c++ Standard says

    An ordinary string literal has type "array of n const char" and static storage duration.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP