12个有趣的C语言面试题(中英文对照)

英文链接:http://www.thegeekstuff.com/2012/08/c-interview-questions/

In this article, we will discuss some interesting problems on C language that can help students to brush up their C programming skills and help them prepare their C fundamentals for interviews.

1. gets() function

Question: There is a hidden problem with the following code. Can you detect it?

#include<stdio.h>

int main(void)
{
    char buff[10];
    memset(buff,0,sizeof(buff));

    gets(buff);

    printf("\n The buffer entered is [%s]\n",buff);

    return 0;
}

Answer: The hidden problem with the code above is the use of the function gets(). This function accepts a string from stdin without checking the capacity of buffer in which it copies the value. This may well result in buffer overflow. The standard function fgets() is advisable to use in these cases.

2. strcpy() function

Question: Following is the code for very basic password protection. Can you break it without knowing the password?

#include<stdio.h>

int main(int argc, char *argv[])
{
    int flag = 0;
    char passwd[10];

    memset(passwd,0,sizeof(passwd));

    strcpy(passwd, argv[1]);

    if(0 == strcmp("LinuxGeek", passwd))
    {
        flag = 1;
    }

    if(flag)
    {
        printf("\n Password cracked \n");
    }
    else
    {
        printf("\n Incorrect passwd \n");

    }
    return 0;
}

Answer: Yes. The authentication logic in above password protector code can be compromised by exploiting the loophole of strcpy() function. This function copies the password supplied by user to the ‘passwd’ buffer without checking whether the length of password supplied can be accommodated by the ‘passwd’ buffer or not. So if a user supplies a random password of such a length that causes buffer overflow and overwrites the memory location containing the default value ’0′ of the ‘flag’ variable then even if the password matching condition fails, the check of flag being non-zero becomes true and hence the password protection is breached.

For example :

$ ./psswd aaaaaaaaaaaaa

 Password cracked

So you can see that though the password supplied in the above example is not correct but still it breached the password security through buffer overflow.

To avoid these kind of problems the function strncpy() should be used.

Note from author : These days the compilers internally detect the possibility of stack smashing and so they store variables on stack in such a way that stack smashing becomes very difficult. In my case also, the gcc does this by default so I had to use the the compile option ‘-fno-stack-protector’ to reproduce the above scenario.

3. Return type of main()

Question: Will the following code compile? If yes, then is there any other problem with this code?

#include<stdio.h>

void main(void)
{
    char *ptr = (char*)malloc(10);

    if(NULL == ptr)
    {
        printf("\n Malloc failed \n");
        return;
    }
    else
    {
        // Do some processing

        free(ptr);
    }

    return;
}

Answer: The code will compile error free but with a warning (by most compilers) regarding the return type of main()function. Return type of main() should be ‘int’ rather than ‘void’. This is because the ‘int’ return type lets the program to return a status value. This becomes important especially when the program is being run as a part of a script which relies on the success of the program execution.

4. Memory Leak

Question: Will the following code result in memory leak?

#include<stdio.h>

void main(void)
{
    char *ptr = (char*)malloc(10);

    if(NULL == ptr)
    {
        printf("\n Malloc failed \n");
        return;
    }
    else
    {
        // Do some processing
    }

    return;
}

Answer: Well, Though the above code is not freeing up the memory allocated to ‘ptr’ but still this would not cause a memory leak as after the processing is done the program exits. Since the program terminates so all the memory allocated by the program is automatically freed as part of cleanup. But if the above code was all inside a while loop then this would have caused serious memory leaks.

Note : If you want to know more on memory leaks and the tool that can detect memory leaks, read our article onValgrind.

5. The free() function

Question: The following program seg-faults (crashes) when user supplies input as ‘freeze’ while it works fine with input ‘zebra’. Why?

#include<stdio.h>

int main(int argc, char *argv[])
{
    char *ptr = (char*)malloc(10);

    if(NULL == ptr)
    {
        printf("\n Malloc failed \n");
        return -1;
    }
    else if(argc == 1)
    {
        printf("\n Usage  \n");
    }
    else
    {
        memset(ptr, 0, 10);

        strncpy(ptr, argv[1], 9);

        while(*ptr != 'z')
        {
            if(*ptr == '')
                break;
            else
                ptr++;
        }

        if(*ptr == 'z')
        {
            printf("\n String contains 'z'\n");
            // Do some more processing
        }

       free(ptr);
    }

    return 0;
}

Answer: The problem here is that the code changes the address in ‘ptr’ (by incrementing the ‘ptr’) inside the while loop. Now when ‘zebra’ is supplied as input, the while loop terminates before executing even once and so the argument passed to free() is the same address as given by malloc(). But in case of ‘freeze’ the address held by ptr is updated inside the while loop and hence incorrect address is passed to free() which causes the seg-fault or crash.

6. atexit with _exit

Question: In the code below, the atexit() function is not being called. Can you tell why?

#include<stdio.h>

void func(void)
{
    printf("\n Cleanup function called \n");
    return;
}

int main(void)
{
    int i = 0;

    atexit(func);

    for(;i<0xffffff;i++);

    _exit(0);
}

Answer: This behavior is due to the use of function _exit(). This function does not call the clean-up functions like atexit() etc. If atexit() is required to be called then exit() or ‘return’ should be used.

7. void* and C structures

Question: Can you design a function that can accept any type of argument and returns an integer? Also, is there a way in which more than one arguments can be passed to it?

Answer: A function that can accept any type of argument looks like :

 int func(void *ptr)

if more than one argument needs to be passed to this function then this function could be called with a structure object where-in the structure members can be populated with the arguments that need to be passed.

8. * and ++ operators

Question: What would be the output of the following code and why?

#include<stdio.h>

int main(void)
{
    char *ptr = "Linux";
    printf("\n [%c] \n",*ptr++);
    printf("\n [%c] \n",*ptr);

    return 0;
}

Answer: The output of the above would be :

[L] 

[i]

Since the priority of both ‘++’ and ‘*’ are same so processing of ‘*ptr++’ takes place from right to left. Going by this logic, ptr++ is evaluated first and then *ptr. So both these operations result in ‘L’. Now since a post fix ‘++’ was applied on ptr so the next printf() would print ‘i’.

9. Making changes in Code(or read-only) segment

Question: The following code seg-faults (crashes). Can you tell the reason why?

#include<stdio.h>

int main(void)
{
    char *ptr = "Linux";
    *ptr = 'T';

    printf("\n [%s] \n", ptr);

    return 0;
}

Answer: This is because, through *ptr = ‘T’, the code is trying to change the first byte of the string ‘Linux’ kept in the code (or the read-only) segment in the memory. This operation is invalid and hence causes a seg-fault or a crash.

10. Process that changes its own name

Question: Can you write a program that changes its own name when run?

Answer: Following piece of code tries to do the required :

#include<stdio.h>

int main(int argc, char *argv[])
{
    int i = 0;
    char buff[100];

    memset(buff,0,sizeof(buff));

    strncpy(buff, argv[0], sizeof(buff));
    memset(argv[0],0,strlen(buff));

    strncpy(argv[0], "NewName", 7);

    // Simulate a wait. Check the process
    // name at this point.
    for(;i<0xffffffff;i++);

    return 0;
}

11. Returning address of local variable

Question: Is there any problem with the following code?If yes, then how it can be rectified?

#include<stdio.h>

int* inc(int val)
{
  int a = val;
  a++;
  return &a;
}

int main(void)
{
    int a = 10;

    int *val = inc(a);

    printf("\n Incremented value is equal to [%d] \n", *val);

    return 0;
}

Answer: Though the above program may run perfectly fine at times but there is a serious loophole in the function ‘inc()’. This function returns the address of a local variable. Since the life time of this local variable is that of the function ‘inc()’ so after inc() is done with its processing, using the address of its local variable can cause undesired results. This can be avoided by passing the address of variable ‘a’ from main() and then inside changes can be made to the value kept at this address.

12. Processing printf() arguments

Question: What would be the output of the following code?

#include<stdio.h>

int main(void)
{
    int a = 10, b = 20, c = 30;

    printf("\n %d..%d..%d \n", a+b+c, (b = b*2), (c = c*2));

    return 0;
}

Answer: The output of the above code would be :

110..40..60

This is because the arguments to the function are processed from right to left but are printed from left to right.

中文链接:http://www.csdn.net/article/2012-09-06/2809604-12-c-interview-questions/1

1.gets()函数

问:请找出下面代码里的问题:

 
 
  1. #include<stdio.h> 
  2. int main(void
  3.     char buff[10]; 
  4.     memset(buff,0,sizeof(buff)); 
  5.  
  6.     gets(buff); 
  7.  
  8.     printf("\n The buffer entered is [%s]\n",buff); 
  9.  
  10.     return 0; 

答:上面代码里的问题在于函数gets()的使用,这个函数从stdin接收一个字符串而不检查它所复制的缓存的容积,这可能会导致缓存溢出。这里推荐使用标准函数fgets()代替。

2.strcpy()函数

问:下面是一个简单的密码保护功能,你能在不知道密码的情况下将其破解吗?

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(int argc, char *argv[]) 
  4.     int flag = 0; 
  5.     char passwd[10]; 
  6.  
  7.     memset(passwd,0,sizeof(passwd)); 
  8.  
  9.     strcpy(passwd, argv[1]); 
  10.  
  11.     if(0 == strcmp("LinuxGeek", passwd)) 
  12.     { 
  13.         flag = 1; 
  14.     } 
  15.  
  16.     if(flag) 
  17.     { 
  18.         printf("\n Password cracked \n"); 
  19.     } 
  20.     else 
  21.     { 
  22.         printf("\n Incorrect passwd \n"); 
  23.  
  24.     } 
  25.     return 0; 

答:破解上述加密的关键在于利用攻破strcpy()函数的漏洞。所以用户在向“passwd”缓存输入随机密码的时候并没有提前检查“passwd”的容量是否足够。所以,如果用户输入一个足够造成缓存溢出并且重写“flag”变量默认值所存在位置的内存的长“密码”,即使这个密码无法通过验证,flag验证位也变成了非零,也就可以获得被保护的数据了。例如:

 
 
  1. $ ./psswd aaaaaaaaaaaaa 
  2.  
  3. Password cracked 

虽然上面的密码并不正确,但我们仍然可以通过缓存溢出绕开密码安全保护。

要避免这样的问题,建议使用 strncpy()函数。

作者注:最近的编译器会在内部检测栈溢出的可能,所以这样往栈里存储变量很难出现栈溢出。在我的gcc里默认就是这样,所以我不得不使用编译命令‘-fno-stack-protector’来实现上述方案。

3.main()的返回类型

问:下面的代码能 编译通过吗?如果能,它有什么潜在的问题吗?

 
 
  1. #include<stdio.h> 
  2.  
  3. void main(void
  4.     char *ptr = (char*)malloc(10); 
  5.  
  6.     if(NULL == ptr) 
  7.     { 
  8.         printf("\n Malloc failed \n"); 
  9.         return
  10.     } 
  11.     else 
  12.     { 
  13.         // Do some processing 
  14.         free(ptr); 
  15.     } 
  16.  
  17.     return

答:因为main()方法的返回类型,这段代码的错误在大多数编译器里会被当作警告。main()的返回类型应该是“int”而不是“void”。因为“int”返回类型会让程序返回状态值。这点非常重要,特别当程序是作为依赖于程序成功运行的脚本的一部分运行时。

4.内存泄露

问:下面的代码会导致内存泄漏吗?

 
 
  1. #include<stdio.h> 
  2.  
  3. void main(void
  4.     char *ptr = (char*)malloc(10); 
  5.  
  6.     if(NULL == ptr) 
  7.     { 
  8.         printf("\n Malloc failed \n"); 
  9.         return
  10.     } 
  11.     else 
  12.     { 
  13.         // Do some processing 
  14.     } 
  15.  
  16.     return

答:尽管上面的代码并没有释放分配给“ptr”的内存,但并不会在程序退出后导致内存泄漏。在程序结束后,所有这个程序分配的内存都会自动被处理掉。但如果上面的代码处于一个“while循环”中,那将会导致严重的内存泄漏问题!

提示:如果你想知道更多关于内存泄漏的知识和内存泄漏检测工具,可以来看看我们在Valgrind上的文章。

5.free()函数

问:下面的程序会在用户输入'freeze'的时候出问题,而'zebra'则不会,为什么?

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(int argc, char *argv[]) 
  4.     char *ptr = (char*)malloc(10); 
  5.  
  6.     if(NULL == ptr) 
  7.     { 
  8.         printf("\n Malloc failed \n"); 
  9.         return -1; 
  10.     } 
  11.     else if(argc == 1) 
  12.     { 
  13.         printf("\n Usage  \n"); 
  14.     } 
  15.     else 
  16.     { 
  17.         memset(ptr, 0, 10); 
  18.  
  19.         strncpy(ptr, argv[1], 9); 
  20.  
  21.         while(*ptr != 'z'
  22.         { 
  23.             if(*ptr == ''
  24.                 break
  25.             else 
  26.                 ptr++; 
  27.         } 
  28.  
  29.         if(*ptr == 'z'
  30.         { 
  31.             printf("\n String contains 'z'\n"); 
  32.             // Do some more processing 
  33.         } 
  34.  
  35.        free(ptr); 
  36.     } 
  37.  
  38.     return 0; 

答:这里的问题在于,代码会(通过增加“ptr”)修改while循环里“ptr”存储的地址。当输入“zebra”时,while循环会在执行前被终止,因此传给free()的变量就是传给malloc()的地址。但在“freeze”时,“ptr”存储的地址会在while循环里被修改,因此导致传给free()的地址出错,也就导致了seg-fault或者崩溃。

6.使用_exit退出

问:在下面的代码中,atexit()并没有被调用,为什么?

 
 
  1. #include<stdio.h> 
  2.  
  3. void func(void
  4.     printf("\n Cleanup function called \n"); 
  5.     return
  6.  
  7. int main(void
  8.     int i = 0; 
  9.  
  10.     atexit(func); 
  11.  
  12.     for(;i<0xffffff;i++); 
  13.  
  14.     _exit(0); 

这是因为_exit()函数的使用,该函数并没有调用atexit()等函数清理。如果使用atexit()就应当使用exit()或者“return”与之相配合。

7.void*和C结构体

问:你能设计一个能接受任何类型的参数并返回interger(整数)结果的函数吗?

答:如下:

 
 
  1. int func(void *ptr) 

如果这个函数的参数超过一个,那么这个函数应该由一个结构体来调用,这个结构体可以由需要传递参数来填充。

8.*和++操作

问:下面的操作会输出什么?为什么?

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(void
  4.     char *ptr = "Linux"
  5.     printf("\n [%c] \n",*ptr++); 
  6.     printf("\n [%c] \n",*ptr); 
  7.  
  8.     return 0; 

答:输出结果应该是这样:

 
 
  1. [L]  
  2.  
  3. [i] 

因为“++”和“*”的优先权一样,所以“*ptr++”相当于“*(ptr++)”。即应该先执行ptr++,然后才是*ptr,所以操作结果是“L”。第二个结果是“i”。

9.问:修改代码片段(或者只读代码)

问:下面的代码段有错,你能指出来吗?

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(void
  4.     char *ptr = "Linux"
  5.     *ptr = 'T'
  6.  
  7.     printf("\n [%s] \n", ptr); 
  8.  
  9.     return 0; 

答:这是因为,通过*ptr = ‘T’,会改变内存中代码段(只读代码)“Linux”的第一个字母。这个操作是无效的,因此会造成seg-fault或者崩溃。

10.会改变自己名字的进程

问:你能写出一个在运行时改变自己进程名的程序吗?

答:参见下面这段代码:

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(int argc, char *argv[]) 
  4.     int i = 0; 
  5.     char buff[100]; 
  6.  
  7.     memset(buff,0,sizeof(buff)); 
  8.  
  9.     strncpy(buff, argv[0], sizeof(buff)); 
  10.     memset(argv[0],0,strlen(buff)); 
  11.  
  12.     strncpy(argv[0], "NewName", 7); 
  13.  
  14.     // Simulate a wait. Check the process 
  15.     // name at this point. 
  16.     for(;i<0xffffffff;i++); 
  17.  
  18.     return 0; 

11.返回本地变量的地址

问:下面代码有问题吗?如果有,该怎么修改?

 
 
  1. #include<stdio.h> 
  2.  
  3. int* inc(int val) 
  4.   int a = val; 
  5.   a++; 
  6.   return &a; 
  7.  
  8. int main(void
  9.     int a = 10; 
  10.     int *val = inc(a); 
  11.     printf("\n Incremented value is equal to [%d] \n", *val); 
  12.  
  13.     return 0; 

答:尽管上面的程序有时候能够正常运行,但是在“inc()”中存在严重的漏洞。这个函数返回本地变量的地址。因为本地变量的生命周期就是“inc()”的生命周期,所以在inc结束后,使用本地变量会发生不好的结果。这可以通过将main()中变量“a”的地址来避免,这样以后还可以修改这个地址存储的值。

12.处理printf()的参数

问:下面代码会输出什么?

 
 
  1. #include<stdio.h> 
  2.  
  3. int main(void
  4.     int a = 10, b = 20, c = 30; 
  5.     printf("\n %d..%d..%d \n", a+b+c, (b = b*2), (c = c*2)); 
  6.  
  7.     return 0; 

答:输出结果是:

 
 
  1. 110..40..60 

这是因为C语言里函数的参数默认是从右往左处理的,输出时是从左往右。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值