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.

stringC

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);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章