zoukankan      html  css  js  c++  java
  • memcpy 导致的段错误

    memcpy 内存复制函数

    在使用时注意不可用字符串,如果是字符串会导致段错误,可以使用asprintf函数复制字符串。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
    	char *id = "this is_$id$_of network!";
    	char *token;
    	
    	if (strstr(id, "$id$") == NULL)
    		return;
    
    	while ((token = strstr(id, "$id$")) != NULL)	
    		memcpy(token, "%s1$", 4);
    
    	return 0;
    }
    

    运行结果

    segmentation-fault
    

    调试查看就是在 memcpy(token,"%s1$",4); 处出错的

    修改

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
    	char *id = "this is_$id$_of network!";
    	char *temId;
    	char Buffer[255];
    	char *token;
    	char *config="12345678",*buffer;
    	
    	if (strstr(id, "$id$") == NULL)
    		return;
    
    	asprintf(&temId,"%s",id);    //在内存中复制一个
    	while ((token = strstr(id, "$id$")) != NULL)	//strstr返回的是地址
    		memcpy(token, "%1$s", 4);                     //这个操作实际上是把原字符串改了
    	
    	printf("token = %s
    ",token);                //token 为空
    	printf("id = %s
    ",id);                            //id 值并没有改变
    	printf("temId = %s
    ",temId);                //temId 被改变了
    	sprintf(Buffer, id, config);                       //字符串操作也可以使用sprintf ,只是第一个参数是已经有空了
    	printf("Buffer = %s
    ",Buffer);
    	sprintf(Buffer, temId, config);
    	printf("Buffer = %s
    ",Buffer);
    	asprintf(&buffer, temId, config);
    	printf("buffer = %s
    ",buffer);
    	return 0;
    }
    

    最后结果

    token = (null)
    id = this is_$id$_of network!
    temId = this is_%1$s_of network!
    Buffer = this is_$id$_of network!
    Buffer = this is_12345678_of network!
    buffer = this is_12345678_of network!
    

    1$

    1$是一个很神奇的东西,它好像一个占位符,会自动消失。并没有搞懂字符串中的$是什么用,好冷,明天再看

  • 相关阅读:
    recurse_array_change_key_case()递规返回字符串键名全为小写或大写的数组
    php循环创建目录
    ajaxFileUpload增加附加参数
    dedecms5.7 联动类型无法显示
    一些比较隐秘的OJ的网址
    Emacs 配置
    qwq
    233
    [八省联考2018]林克卡特树lct
    [APIO2014]序列分割
  • 原文地址:https://www.cnblogs.com/tianmo/p/7955223.html
Copyright © 2011-2022 走看看