The understanding of string in C.

For c language, the string is a kind of abstract data type, which can be defined as a char string.

 

char str[256];

However, what's is the length of a string. For example:

scanf("%s", str);

If use input:

abc<CR>

So, all of us know the length of str is 3, which can be calculated with lib function strlen.

int len = strlen(str);

Now, we have the following code segment:

char str[256];
scanf("%s", str);
char *a = (char*)malloc(strlen(str));
strcpy(a, str);
printf("%s\n", a);
free(a);

Is the above code right? If no, find the problem and explain why.

If you run the above code in Visual studio 2010(I didn't test it in other IDE), it will prompt that "HEAP CORRUPTION DETECTED: after...". What's problem.

In fact, a default char will be added to mark the end of string in C language, it's NUL.  Look at the following snapshot of a watch window.

You can see there is a '0' at the end of str, which is the ASCII of '\0'. Therefore, we can see that the actual size of a string in C should be strlen()+1. In above code, the function free() will release the memory space which has been allocated by malloc, i.e., strlen(str). To correct it, we should take the end sign of string into account and we get:

char str[256];
scanf("%s", str);
char *a = (char*)malloc(strlen(str)+1);
strcpy(a, str);
printf("%s\n", a);
free(a);

At last, leave a question! 

typedef struct node{
       char* name;
       struct node* next;
}Node;

//The following code is correct or not?
  Node* a = (Node*)malloc(sizeof(struct node));
  if(a)
  {
	  char str[256];
	  scanf("%s", str);
	  a->name = (char*)malloc(strlen(str));
	  strcpy(a->name, str);
	  a->next = NULL;
  }
  free(a);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值