Tuesday, 17 April 2012

Common mistakes in C programming


Common mistakes about subfunction:

1. Formal parameter issues:
 
void GetMemory(char *p)
{
p = (char *)malloc(100);
}

void Test(void)
{
char *str = NULL;
GetMemory(str);  
strcpy(str, "hello world");
printf(str);
}
Using a pointer variable as formal parameter is dangerous, because formal parameter only passes the value. So it only pass the address. 

So when allocate memory to formal paramter or any other defined pointer variables in subfunction, it will disapear after the end of subfunction. Insteadly, we can achieve the same function by passing the pointer variable who points the pointer variable who is going to be allocated.
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
if(*p==NULL)
printf(" Memory allocation fails!\n ");
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");  
printf(str);   
}

2. Variable life in subfunction:

char *GetMemory(void)
{  
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str= GetMemory();   
printf(str);
}

This program may not print the string "hello world", because although GetMemory function can return the address of the string, but the content has been destroyed after the end of the subfunction.

Monday, 16 April 2012

Pointer variable


Usually, pointer variables are with type difinition like char *int *long *, and like that. So when you want to  do some operations, compiler will use sizeof(type) as the unit. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    int *point1;
    point1=a;
    point1=point1+1;
    printf("%d\n", *point1);
    getchar();
}

Result: 5

However, we can use void * to define a point variable without type. But this variable cannot be operated because of the uncertain length of this variable. So before operation, you have to cast the variable to a specific type to do the operations. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    void *point2;

    point2=a;

    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);

    getchar();
}
Result:
1280  --- 00000101  00000000
5
1536  --- 00000110  00000000
6



Reference:
[1] C语言深度解剖读书笔记之----C语言基础测试题, http://blog.csdn.net/feitianxuxue/article/details/7334929

Difference between "docker stop" and "docker kill"

 To stop a running container, you can use either "docker stop" or "docker kill" command to do so. Although it seems doin...