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\n",token);                //token 為空
	printf("id = %s\n",id);                            //id 值並沒有改變
	printf("temId = %s\n",temId);                //temId 被改變了
	sprintf(Buffer, id, config);                       //字符串操作也可以使用sprintf ,只是第一個參數是已經有空了
	printf("Buffer = %s\n",Buffer);
	sprintf(Buffer, temId, config);
	printf("Buffer = %s\n",Buffer);
	asprintf(&buffer, temId, config);
	printf("buffer = %s\n",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$是一個很神奇的東西,它好像一個占位符,會自動消失。並沒有搞懂字符串中的$是什么用,好冷,明天再看


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM