C language to find out the real driver problem, the ten most must-have questions in the C language interview, a must-see for job hunting!!!

The suspected violation of this floor has been folded by the system. Hide this floor to view this floor

6. free() function

Q: The following program fails when the user types 'freeze', but not 'zebra', why?

#include 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 modifies (by incrementing "ptr") the address where "ptr" is stored in the while loop. When "zebra" is entered, the while loop is terminated before execution, so the variable passed to free() is the address passed to malloc(). But when "freeze", the address stored by "ptr" will be modified in the while loop, thus causing the address passed to free() to be wrong, which also leads to seg-fault or crash.

7. * and ++ operations

Q: What will the following operation output? Why?

#include int main(void) {

char *ptr = "Linux";

printf("\n [%c] \n",*ptr++);

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

return 0; }

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

[L] [i]

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324482057&siteId=291194637