memset, string, 段错误?---谈谈我遇到的memset误用

972 篇文章 329 订阅
309 篇文章 11 订阅

     1. 字符串:

 

#include <iostream>
using namespace std;

int main()
{
	char str[100] = "abc";

	int a = int(str);
	int b = int(&str);
	
	if(a == b)
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}

	return 0;
}

       结果是yes, 可见, str和&str的值是相同的。 仅仅是值相同。
 

 

      看看下面的程序:

 

#include <iostream>
using namespace std;

int main()
{
	char str[100] = "abc";
	memset(&str, 0, sizeof(str));

	return 0;
}

      上面程序有错误, 但是, 运气够好的, &str刚好和str相等。应该改为:

 

 

#include <iostream>
using namespace std;

int main()
{
	char str[100] = "abc";
	memset(str, 0, sizeof(str));

	return 0;
}

 

 

 

 

 

       2. 整数

 

#include <iostream>
using namespace std;

int main()
{
	int a[100];
	memset(a, 0, 100);

	int i = 0;
	for(i = 0; i < 100; i++)
	{
		cout << a[i] << endl; // 很多都非零
	}

	return 0;
}


       应该改为:

 

 

#include <iostream>
using namespace std;

int main()
{
	int a[100];
	memset(a, 0, 100 * sizeof(int));

	int i = 0;
	for(i = 0; i < 100; i++)
	{
		cout << a[i] << endl; //全部为0
	}

	return 0;
}

      或者改为更好的:

 

 

#include <iostream>
using namespace std;

int main()
{
	int a[100];
	memset(a, 0, sizeof(a));

	int i = 0;
	for(i = 0; i < 100; i++)
	{
		cout << a[i] << endl;
	}

	return 0;
}

      当然, 如果是初始化, 用int a[100] = {0}; 也未尝不可。
 

 

      3. c++ string

      骇人听闻的段错误,下面程序, 在vc++6.0中居然不报错:

 

#include <iostream>
#include <string>
using namespace std;

typedef struct _test
{
	int score;
	string name;
}Student;

int main()
{
	Student a;
	memset(&a, 0, sizeof(a));

	a.name = "lily";
	cout << a.name.c_str() << endl;

	return 0;
}

      如果在linux, 运行程序, 就会出现段错误, 原因:string不能memset, 为什么? 查查memset的用法吧。 最近在实际中遇到了这个问题, 略作记录, 请大家注意。

 

 

      最后再补充一个, 内存重叠时, 不要用memcpy, 要用memmove.

 

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值