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

原文地址:https://www.cnblogs.com/tianmo/p/7955223.html