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

  • 相关阅读:
    第二章:Java内存区域
    第六章:内核数据结构
    第十章:内核同步方法
    第九章:内核同步介绍
    第九章:zookeeper内部原理
    第三章:开始使用zookeeper的API
    第二章:了解zookeeper
    【观点】健康的心智是中国未来最大的生产力
    【流程管理分享】人事不分,问题不断
    为什么中国人勤劳而不富裕?为什么宋朝富裕而不强大?
  • 原文地址:https://www.cnblogs.com/tianmo/p/7955223.html
Copyright © 2011-2022 走看看