Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

search topic

Showing posts with label C language latest technical interview questions and answers. Show all posts
Showing posts with label C language latest technical interview questions and answers. Show all posts

Wednesday, August 6, 2008

IMP interview questions C language Technical Interview Questions for 2008

C computer language programming / technical interview questions and answers with programs detailes solutions free online for various top IT companies in India and US. freshers and on campus interviews and placement papers.

. What will print out?
main()
{
char *k1="hitechskill.com";
char *k2;
k2=(char*)malloc(20);
memset (k2, 0, 20);
while(*k2++ = *k1++);
printf("%s\n",k2);

}

Answer:empty string.


2.What will be printed as the result of the operation below:

main()
{
int a=20,b=35;
a=b++ + a++;
b= ++b + ++a;
printf("%d%d\n",a,b);

}
Answer : 5794

3.What will be printed as the result of the operation below:
main()
{
int a=5;
printf(?%d,%d,%d\n?,a,a< <2,a>>2);
}
Answer: 5,20,1

4.What will be printed as the result of the operation below:
#define swap(a,b) a=a+b;b=a-b;a=a-b;
void main()
{
int m=5, n=10;
swap (m,n);
printf("%d %d\n",m,n);
swap2(m,n);
printf("%d %d\n",m,n);
}

int swap2(int x, int y)
{
int temp;
temp=x;
y=x;
x=temp;
return 0;

}
Answer: 10, 5
10, 5


5.What will be printed as the result of the operation below:
main()
{
char *ptr = "SC Systems";
*pt++; printf("%s\n",pt);
pt++;
printf("%s\n",pt);

}
Answer: SC Systems
C Systems

6.What will be printed as the result of the operation below:
main()
{
char s1[]="SC";
char s2[]= "Systems";
printf("%s",s1);
}
Answer: SC

7.What will be printed as the result of the operation below:
main()
{
char *ptr1;
char *ptr2;

ptr1=(char *)malloc(25);
ptr2=(char *)malloc(25);

strcpy(ptr1,"SC");
strcpy(ptr2,"Systems");
strcat(ptr1,ptr2);

printf("%s",ptr1);

}
Answer: SCSystems


8.The following variable is available in file1.c, who can access it?:
static int average;
Answer: all the functions in the file1.c can access the variable.

9.What will be the result of the following code?
#define TRUE 0 // some code
while(TRUE)
{

// some code

}
Answer: This will not go into the loop as TRUE is defined as 0.

10.What will be printed as the result of the operation below:
int x;
int modifyvalue()
{
return(x+=10);
}

int changevalue(int x)
{
return(x+=1);
}

void main()
{
int x=10;
x++;
changevalue(x);
x++;
modifyvalue();
printf("First output:%d\n",x);

x++;
changevalue(x);
printf("Second output:%d\n",x);
modifyvalue();
printf("Third output:%d\n",x);

}
Answer: 12 , 13 , 13

11.What will be printed as the result of the operation below:
main()
{
int x=10, y=15;
x = x++;
y = ++y;
printf("%d %d\n",x,y);

}
Answer: 11, 16

12.What will be printed as the result of the operation below:
main()
{
int a=0;
if(a==0)
printf("Cisco Systems\n");
printf("Cisco Systems\n");

}
Answer: Two lines with "Cisco Systems" will be printed.

IMP interview questions C language Important Technical Interview Questions 2008

Mostly asked / recent - latest technical interview questions for 2008 for various leading IT and other Indian, Multinational Companies / MNCs placement paper basic / advanced questions, c language programs asked List.

1.

What does static variable mean?
2.

What is a pointer?
3.

What is a structure?
4.

What are the differences between structures and arrays?
5.

In header files whether functions are declared or defined?
6.

What are the differences between malloc() and calloc()?
7.

What are macros? What are the advantages and disadvantages?
8.

Difference between pass by reference and pass by value?
9.

What is static identifier?
10.

Where are the auto variables stored?
11.

Where does global, static, local, register variables, free memory and C Program instructions get stored?
12.

Difference between arrays and linked list?
13.

What are enumerations?
14.

Describe about storage allocation and scope of global, extern, static, local and register variables?
15.

What are register variables? What are the advantage of using register variables?
16.

What is the use of typedef?
17.

Can we specify variable field width in a scanf() format string? If possible how?
18.

Out of fgets() and gets() which function is safe to use and why?
19.

Difference between strdup and strcpy?
20.

What is recursion?
21.

Differentiate between a for loop and a while loop? What are it uses?
22.

What are the different storage classes in C?
23.

Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
24.

What is difference between Structure and Unions?
25.

What the advantages of using Unions?
26.

What are the advantages of using pointers in a program?
27.

What is the difference between Strings and Arrays?
28.

In a header file whether functions are declared or defined?
29.

What is a far pointer? where we use it?
30.

How will you declare an array of three function pointers where each function receives two ints and returns a float?
31.

What is a NULL Pointer? Whether it is same as an uninitialized pointer?
32.

What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
33.

What does the error ?Null Pointer Assignment? mean and what causes this error?
34.

What is near, far and huge pointers? How many bytes are occupied by them?
35.

How would you obtain segment and offset addresses from a far address of a memory location?
36.

Are the expressions arr and *arr same for an array of integers?
37.

Does mentioning the array name gives the base address in all the contexts?
38.

Explain one method to process an entire string as one unit?
39.

What is the similarity between a Structure, Union and enumeration?
40.

Can a Structure contain a Pointer to itself?
41.

How can we check whether the contents of two structure variables are same or not?
42.

How are Structure passing and returning implemented by the complier?
43.

How can we read/write Structures from/to data files?
44.

What is the difference between an enumeration and a set of pre-processor # defines?
45.

What do the ?c? and ?v? in argc and argv stand for?
46.

Are the variables argc and argv are local to main?
47.

What is the maximum combined length of command line arguments including the space between adjacent arguments?
48.

If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?
49.

Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
50.

What are bit fields? What is the use of bit fields in a Structure declaration?
51.

To which numbering system can the binary number 1101100100111100 be easily converted to?
52.

Which bit wise operator is suitable for checking whether a particular bit is on or off?
53.

Which bit wise operator is suitable for turning off a particular bit in a number?
54.

Which bit wise operator is suitable for putting on a particular bit in a number?
55.

Which bit wise operator is suitable for checking whether a particular bit is on or off?
56.

Which one is equivalent to multiplying by 2?
Left shifting a number by 1
Left shifting an unsigned int or char by 1?
57.

Write a program to compare two strings without using the strcmp() function.
58.

Write a program to concatenate two strings.
59.

Write a program to interchange 2 variables without using the third one.
60.

Write programs for String Reversal. The same for Palindrome check.
61.

Write a program to find the Factorial of a number.
62.

Write a program to generate the Fibonacci Series?
63.

Write a program which employs Recursion?
64.

Write a program which uses command line arguments.
65.

Write a program which uses functions like strcmp(), strcpy(), etc.
66.

What are the advantages of using typedef in a program?
67.

How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
68.

How can you increase the size of a dynamically allocated array?
69.

How can you increase the size of a statically allocated array?
70.

When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
71.

Which function should be used to free the memory allocated by calloc()?
72.

How much maximum can you allocate in a single call to malloc()?
73.

Can you dynamically allocate arrays in expanded memory?
74.

What is object file? How can you access object file?
75.

Which header file should you include if you are to develop a function which can accept variable number of arguments?
76.

Can you write a function similar to printf()?
77.

How can a called function determine the number of arguments that have been passed to it?
78.

Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
79.

How do you declare the following:
An array of three pointers to chars
An array of three char pointers
A pointer to array of three chars
A pointer to function which receives an int pointer and returns a float pointer
A pointer to a function which receives nothing and returns nothing
80.

What do the functions atoi(), itoa() and gcvt() do?
81.

Does there exist any other function which can be used to convert an integer or a float to a string?
82.

How would you use qsort() function to sort an array of structures?
83.

How would you use qsort() function to sort the name stored in an array of pointers to string?
84.

How would you use bsearch() function to search a name stored in array of pointers to string?
85.

How would you use the functions sin(), pow(), sqrt()?
86.

How would you use the functions memcpy(), memset(), memmove()?
87.

How would you use the functions fseek(), freed(), fwrite() and ftell()?
88.

How would you obtain the current time and difference between two times?
89.

How would you use the functions randomize() and random()?
90.

How would you implement a substr() function that extracts a sub string from a given string?
91.

What is the difference between the functions rand(), random(), srand() and randomize()?
92.

What is the difference between the functions memmove() and memcpy()?
93.

How do you print a string on the printer?
94.

Can you use the function fprintf() to display the output on the screen?
95.

What is a linklist and why do we use it when we have arrays? - I feel the correct answer should be linklist is used in cases where you don?t know the memory required to store a data structure and need to allocate is dynamically on demand.
96.

How do you detect a loop in linked list?
97.

What is the difference between main() in C and main() in C++?
98.

what will be printed out when the following code is executed:
main()
{
printf("%x",-1<<4);>

IMP interview questions C language technical interview questions with answers and solved programs - 4

C language questions on Structures / unions / enumerations

1. What's the difference between these two declarations?
struct x1 { ... };
typedef struct { ... } x2;

A: The first form declares a "structure tag"; the second declares a "typedef". The main difference is that you subsequently refer to the first type as "struct x1" and the second simply as "x2".That is, the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure,and the keyword struct is not used when declaring instances of it.

2. Why doesn't work the following code ?

struct x { ... };
x thestruct;
A: C is not C++. Typedef names are not automatically generated for structure tags.

3.Can a structure contain a pointer to itself?
A: Most certainly.

4. What's the best way of implementing opaque (abstract) data types in C?
A: One good way is for clients to use structure pointers (perhaps additionally hidden behind typedefs) which point to structure types which are not publicly defined.

5. I came across some code that declared a structure like this:
struct name {
int namelen;
char namestr[1];
};
and then did some tricky allocation to make the namestr array act like it had several elements. Is this legal or portable?

A: This technique is popular, although Dennis Ritchie has called it "unwarranted chumminess with the C implementation." An official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.) Another possibility is to declare the variable-size element very large, rather than very small; in the case of the above example:
...
char namestr[MAXSIZE];
where MAXSIZE is larger than any name which will be stored. However, it looks like this technique is disallowed by a strict interpretation of the Standard as well. Furthermore, either of these "chummy" structures must be used with care, since the programmer knows more about their size than the compiler does. (In particular, they can generally only be manipulated via pointers.)

C9X will introduce the concept of a "flexible array member", which will allow the size of an array to be omitted if it is the last member in a structure, thus providing a well-defined solution.

6. Is there a way to compare structures automatically?
A: No. There is no single, good way for a compiler to implement implicit structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct; A field-by-field comparison might require unacceptable amounts of repetitive code for large structures.

If you need to compare two structures, you'll have to write your own function to do so, field by field.

7. How can I pass constant values to functions which accept structure arguments?
A: As of this writing, C has no way of generating anonymous structure values. You will have to use a temporary structure variable or a little structure-building function.
The C9X Standard will introduce "compound literals"; one form of compound literal will allow structure constants. For example, to pass a constant coordinate pair to a plotpoint() function which expects a struct point, you will be able to call
plotpoint((struct point){1, 2});
Combined with "designated initializers" (another C9X feature), it will also be possible to specify member values by name:
plotpoint((struct point){.x=1, .y=2});

8. How can I read/write structures from/to data files?

A: It is relatively straightforward to write a structure out using fwrite():
fwrite(&somestruct, sizeof somestruct, 1, fp);
and a corresponding fread invocation can read it back in.However, data files so written will *not* be portable. Note also that if the structure contains any pointers, only the pointer values will be written,
and they are most unlikely to be valid when read back in. Finally, note that for widespread portability you must use the "b" flag when fopening the files;
A more portable solution, though it's a bit more work initially, is to write a pair of functions for writing and reading a structure, field-by-field, in a portable (perhaps even human- readable) way.

9. My compiler is leaving holes in structures, which is wasting space and preventing "binary" I/O to external data files. Can I turn off the padding, or otherwise control the alignment of structure fields?

A: Your compiler may provide an extension to give you this control (perhaps a #pragma; but there is no standard method.

10. Why does sizeof report a larger size than I expect for a structure type, as if there were padding at the end?
A: Structures may have this padding (as well as internal padding), if necessary, to ensure that alignment properties will be preserved when an array of contiguous structures is allocated. Even when the structure is not part of an array, the end padding remains, so that sizeof can always return a consistent size.

11. How can I determine the byte offset of a field within a structure?
A: ANSI C defines the offsetof() macro, which should be used if available; see <>. If you don't have it, one possible implementation is
#define offsetof(type, mem) ((size_t) \ ((char *)&((type *)0) > mem - (char *)(type *)0))
This implementation is not 100% portable; some compilers may legitimately refuse to accept it.

12. How can I access structure fields by name at run time?
A: Build a table of names and offsets, using the offsetof() macro. The offset of field b in struct a is
offsetb = offsetof(struct a, b)
If structp is a pointer to an instance of this structure, and field b is an int (with offset as computed above), b's value can be set indirectly with
*(int *)((char *)structp + offsetb) = value;

13. This program works correctly, but it dumps core after it finishes. Why?
struct list {
char *item;
struct list *next;
}
/* Here is the main program. */
main(argc, argv)
{ ... }

A: A missing semicolon causes main() to be declared as returning a structure. (The connection is hard to see because of the intervening comment.) Since structure-valued functions are usually implemented by adding a hidden return pointer, the generated code for main() tries to accept three arguments, although only two are passed (in this case, by the C start-up
code).

14. Can I initialize unions?
A: The current C Standard allows an initializer for the first-named member of a union. C9X will introduce "designated initializers" which can be used to initialize any member.

15. What is the difference between an enumeration and a set of preprocessor #defines?
A: At the present time, there is little difference. The C Standard says that enumerations may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)

Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations and integers are indiscriminately mixed, since doing so can still be considered
bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables.

16. Is there an easy way to print enumeration values symbolically?
A: No. You can write a little function to map an enumeration constant to a string. (For debugging purposes, a good debugger should automatically print enumeration constants symbolically.)

keep looking for more c language and other computer languages technical, hr interview questions with solutions / answers in details for reputed indian and foreign companies recent and previous years placement papers.

IMP interview questions C language Technical Interview 2008 questions 5

Expressions

. Why doesn't this code:
a[i] = i++;
work?
A: The subexpression i++ causes a side effect -- it modifies i's value -- which leads to undefined behavior since i is also referenced elsewhere in the same expression, and there's no way to determine whether the reference (in a[i] on the left-hand side) should be to the old or the new value. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined.

2. Under my compiler, the code
int i = 7;
printf("%d\n", i++ * i++);
prints 49. Regardless of the order of evaluation, shouldn't it print 56?

A: Although the postincrement and postdecrement operators ++ and -- perform their operations after yielding the former value, the implication of "after" is often misunderstood. It is *not* guaranteed that an increment or decrement is performed immediately after giving up the previous value and before any other part of the expression is evaluated. It is merely guaranteed that the update will be performed sometime before the expression is considered "finished" (before the next "sequence
point," in ANSI C's terminology; ). In the example, the compiler chose to multiply the previous value by itself and to perform both increments afterwards.

The behavior of code which contains multiple, ambiguous side effects has always been undefined. (Loosely speaking, by "multiple, ambiguous side effects" we mean any combination of ++, --, =, +=, -=, etc. in a single expression which causes the same object either to be modified twice or modified and then inspected. This is a rough definition; Don't even try to find out how your compiler implements such things (contrary to the ill-advised exercises in many C
textbooks);

3. I've experimented with the code
int i = 3;
i = i++;
on several compilers. Some gave i the value 3, and some gave 4. Which compiler is correct?

A: There is no correct answer; the expression is undefined. Also, note that neither i++ nor ++i is the same as i+1. If you want to increment i, use i=i+1, i+=1, i++, or ++i, not some combination.

4. Here's a slick expression:
a ^= b ^= a ^= b
It swaps a and b without using a temporary.
A: Not portably, it doesn't. It attempts to modify the variable a twice between sequence points, so its behavior is undefined.
For example, it has been reported that when given the code
int a = 123, b = 7654;
a ^= b ^= a ^= b;
the SCO Optimizing C compiler (icc) sets b to 123 and a to 0.

5. Can I use explicit parentheses to force the order of evaluation I want? Even if I don't, doesn't precedence dictate it?
A: Not in general.
Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression. In the expression
f() + g() * h()
although we know that the multiplication will happen before the addition, there is no telling which of the three functions will be called first.
When you need to ensure the order of subexpression evaluation, you may need to use explicit temporary variables and separate statements.

6. But what about the && and operators?
I see code like "while((c = getchar()) != EOF && c != '\n')" ...
A: There is a special "short-circuiting" exception for those operators. The right-hand side is not evaluated if the left- hand side determines the outcome (i.e. is true for or false for &&). Therefore, left-to-right evaluation is guaranteed, as it also is for the comma operator. Furthermore, all of these operators (along with ?:) introduce an extra internal sequence point

7. How can I understand these complex expressions? What's a "sequence point"?
A: A sequence point is a point in time (at the end of the evaluation of a full expression, or at the , &&, ?:, or comma operators, or just before a function call) at which the dust has settled and all side effects are guaranteed to be complete. The ANSI/ISO C Standard states that
Between the previous and next sequence point an object shall have its stored value modified at
most once by the evaluation of an expression. Furthermore, the prior value shall be accessed
only to determine the value to be stored.
The second sentence can be difficult to understand. It says that if an object is written to within a full expression, any and all accesses to it within the same expression must be for the purposes of computing the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

8. So given
a[i] = i++;
we don't know which cell of a[] gets written to, but i does get incremented by one, right?
A: *No*. Once an expression or program becomes undefined, *all* aspects of it become undefined. See questions 3.2, 3.3, 11.33, and 11.35.

9. If I'm not using the value of the expression, should I use i++ or ++i to increment a variable?
A: Since the two forms differ only in the value yielded, they are entirely equivalent when only their side effect is needed. (However, the prefix form is preferred in C++.)

10. Why doesn't the code
int a = 1000, b = 1000;
long int c = a * b;
work?
A: Under C's integral promotion rules, the multiplication is carried out using int arithmetic, and the result may overflow or be truncated before being promoted and assigned to the long int left-hand side. Use an explicit cast to force long arithmetic:
long int c = (long int)a * b;
Note that (long int)(a * b) would *not* have the desired effect.
A similar problem can arise when two integers are divided, with the result assigned to a floating-point variable; the solution is similar, too.

11. I have a complicated expression which I have to assign to one of two variables, depending on a condition. Can I use code like this?
((condition) ? a : b) = complicated_expression;
A: No. The ?: operator, like most operators, yields a value, and you can't assign to a value. (In other words, ?: does not yield an "lvalue".) If you really want to, you can try something like
*((condition) ? &a : &b) = complicated_expression;
although this is admittedly not as pretty.

IMP interview questions C language pointers questions - 6

C language important latest / recent technical interview questions on pointers 2008 asked commonly by reputed IT companies in India for on campus / walk in interviews for freshers. Real candidates' notes Complete with detail answers / solutions

1. I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code?
char *p;
*p = malloc(10);
A: The pointer you declared is p, not *p. To make a pointer point somewhere, you just use the name of the pointer:
p = malloc(10);
It's when you're manipulating the pointed-to memory that you use * as an indirection operator:
*p = 'H';

2. Does *p++ increment p, or what it points to?
A: Postfix ++ essentially has higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented. To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, if the order of the side effect doesn't matter).

3. I have a char * pointer that happens to point to some ints, and I want to step it over them. Why doesn't
((int *)p)++;
work?
A: In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a delibrate but nonstandard extension if a particular compiler accepts expressions such as the above.) Say what you mean: use
p = (char *)((int *)p + 1);
or (since p is a char *) simply
p += sizeof(int);

Whenever possible, you should choose appropriate pointer types in the first place, instead of trying to treat one type as another.

4. I have a function which accepts, and is supposed to initialize, a pointer:
void f(int *ip)
{
static int dummy = 5;
ip = &dummy;
}
But when I call it like this:
int *ip;
f(ip);
the pointer in the caller remains unchanged.

A: Are you sure the function initialized what you thought it did? Remember that arguments in C are passed by value. The called function altered only the passed copy of the pointer. You'll either want to pass the address of the pointer (the function will end up accepting a pointer-to-a-pointer), or have the function return the pointer.

5. Can I use a void ** pointer as a parameter so that a function can accept a generic pointer by reference?
A: Not portably. There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed (the correct underlying pointer type is not known) if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *.

6.I have a function extern int f(int *); which accepts a pointer to an int. How can I pass a constant by reference? A call like f(&5); doesn't seem to work.
A: You can't do this directly. You will have to declare a temporary variable, and then pass its address to the function:
int five = 5;
f(&five);

7. Does C even have "pass by reference"?
A: Not really. Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function (by passing a pointer instead). However, C has nothing truly equivalent to formal pass by reference or C++ reference parameters. (On the other hand, function-like preprocessor macros can provide a form of "pass by name".)

8. I've seen different methods used for calling functions via pointers. What's the story?
A: Originally, a pointer to a function had to be "turned into" a "real" function, with the * operator (and an extra pair of parentheses, to keep the precedence straight), before calling:
int r, func(), (*fp)() = func;
r = (*fp)();
It can also be argued that functions are always called via pointers, and that "real" function names always decay implicitly into pointers (in expressions, as they do in initializations;). This reasoning (which is in fact used in the ANSI standard) means that
r = fp();
is legal and works correctly, whether fp is the name of a function or a pointer to one. (The usage has always been unambiguous; there is nothing you ever could have done with a function pointer followed by an argument list except call the function pointed to.) An explicit * is still allowed.

For more computer language resources / notes / project / interview questions and answers help keep watching PreviousPapers.blogspot.com

IMP interview questions C language technical interview questions - 7

C language Null pointers questions asked in technical interviews of reputed companies - 2008

1. What is this infamous null pointer, anyway?
A: The language definition states that for each pointer type, there is a special value -- the "null pointer" -- which is distinguishable from all other pointer values and which is "guaranteed to compare unequal to a pointer to any object or function." That is, the address-of operator & will never yield a null pointer, nor will a successful call to malloc(). (malloc() does return a null pointer when it fails, and this is a typical use of null pointers: as a "special" pointer value with some other meaning, usually "not allocated" or "not pointing anywhere yet.")

A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object or function; an uninitialized pointer might point anywhere.

As mentioned above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different. Although programmers need not know the internal values, the compiler must always be informed which type of null pointer is required, so that it can make the distinction if necessary

2. How do I get a null pointer in my programs?
A: According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time. That is, in an initialization, assignment, or comparison when one side is a variable or expression of pointer type, the compiler can tell that a constant 0 on the other side requests a null pointer, and generate the correctly-typed null pointer value. Therefore, the following fragments are perfectly legal:

char *p = 0;
if(p != 0)

However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. To generate a null pointer in a function call context, an explicit cast may be required, to force the 0 to be recognized as a pointer. For example, the Unix system call execl takes a variable-length, null-pointer-terminated list of character pointer arguments, and is correctly called like this:

execl("/bin/sh", "sh", "-c", "date", (char *)0);

If the (char *) cast on the last argument were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead. (Note that many Unix manuals get this example wrong.)

When function prototypes are in scope, argument passing becomes an "assignment context," and most casts may safely be omitted, since the prototype tells the compiler that a pointer is
required, and of which type, enabling it to correctly convert an unadorned 0. Function prototypes cannot provide the types for variable arguments in variable-length argument lists however, so
explicit casts are still required for those arguments. It is probably safest to properly cast all null pointer constants in function calls, to guard against varargs functions or those without prototypes.

Unadorned 0 okay: Explicit cast required:
initialization function call, no prototype in scope assignment variable argument in comparison varargs function call

function call, prototype in scope, fixed argument

3. Is the abbreviated pointer comparison "if(p)" to test for non- null pointers valid? What if the internal representation for null pointers is nonzero?
A: When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes
if(expr)
where "expr" is any expression at all, the compiler essentially acts as if it had been written as
if((expr) != 0)
Substituting the trivial pointer expression "p" for "expr", we have
if(p) is equivalent to if(p != 0)
and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does *not* matter.
The boolean negation operator, !, can be described as follows:
!expr is essentially equivalent to (expr)?0:1 or to ((expr) == 0)
which leads to the conclusion that
if(!p) is equivalent to if(p == 0)
"Abbreviations" such as if(p), though perfectly legal, are considered by some to be bad style

4. What is NULL and how is it #defined?
A: As a matter of style, many programmers prefer not to have unadorned 0's scattered through their programs. Therefore, the preprocessor macro NULL is #defined (by and several
other headers) with the value 0, possibly cast to (void *). A programmer who wishes to make explicit
the distinction between 0 the integer and 0 the null pointer constant can then use NULL whenever a null pointer is required.

Using NULL is a stylistic convention only; the preprocessor turns NULL back into 0 which is then recognized by the compiler, in pointer contexts, as before. In particular, a cast may still
be necessary before NULL (as before 0) in a function call argument. T

5. How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer?
A: The same as on any other machine: as 0 (or some version of 0;).
Whenever a programmer requests a null pointer, either by writing "0" or "NULL", it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer. Therefore, #defining NULL as 0 on a machine for which internal null pointers are nonzero is as valid as on any other: the compiler must always be able to generate the machine's correct null pointers in response to unadorned 0's seen in pointer contexts.

6. If NULL were defined as follows:
#define NULL ((char *)0)
wouldn't that make function calls which pass an un cast NULL work?

A: Not in general. The complication is that there are machines which use different internal representations for pointers to different types of data. The suggested definition would make
uncast NULL arguments to functions expecting pointers to characters work correctly, but pointer arguments of other types would still be problematical, and legal constructions such as
FILE *fp = NULL;
could fail.
Nevertheless, ANSI C allows the alternate definition
#define NULL ((void *)0)
for NULL. Besides potentially helping incorrect programs to work (but only on machines with homogeneous pointers, thus questionably valid assistance), this definition may catch
programs which use NULL incorrectly (e.g. when the ASCII NULL character was really intended;).

7.If NULL and 0 are equivalent as null pointer constants, which should I use?
A: Many programmers believe that NULL should be used in all pointer contexts, as a reminder that the value is to be thought of as a pointer. Others feel that the confusion surrounding NULL and 0
is only compounded by hiding 0 behind a macro, and prefer to use unadorned 0 instead. There is no one right answer. C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's.

NULL should *not* be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of
NULL to be ((void *)0), which will not work at all in non- pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition

#define NUL '\0'
if you must.

8. But wouldn't it be better to use NULL (rather than 0), in case the value of NULL changes, perhaps on a machine with nonzero internal null pointers?

A: No. (Using NULL may be preferable, but not for this reason.) Although symbolic constants are often used in place of numbers because the numbers might change, this is *not* the reason that
NULL is used in place of 0. Once again, the language guarantees that source-code 0's (in pointer contexts) generate null pointers. NULL is used only as a stylistic convention.

9. I use the preprocessor macro
#define Nullptr(type) (type *)0
to help me build null pointers of the correct type.
A: This trick, though popular and superficially attractive, does
not buy much. It is not needed in assignments or comparisons;
(It does not even save keystrokes.)

10. This is strange. NULL is guaranteed to be 0, but the null pointer is not?
A: When the term "null" or "NULL" is casually used, one of several
things may be meant:

1. The conceptual null pointer
2. The internal (or run-time) representation of a null pointer, which may or may not be all-bits-0 and which may be different for different pointer types. The actual values should be of concern only to compiler writers. Authors of C programs never see them, since they use...
3. The null pointer constant, which is a constant integer 0 It is often hidden behind...
4. The NULL macro, which is #defined to be 0 Finally, as red herrings, we have...
5. The ASCII null character (NUL), which does have all bits zero, but has no necessary relation to the null pointer except in name; and...
6. The "null string," which is another name for the empty string (""). Using the term "null string" can be confusing in C, because an empty string involves a null ('\0') character, but *not* a null pointer, which brings us full circle...

11.Why is there so much confusion surrounding null pointers? Why do these questions come up so often?
A: C programmers traditionally like to know more than they might need to about the underlying machine implementation. The fact that null pointers are represented both in source code, and
internally to most machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day, or on some weird machine. The construct "if(p == 0)" is easily misread as calling for conversion of p to an integral type, rather than 0 to a pointer type, before the comparison. Finally, the distinction between the several uses of the term "null" is often overlooked.

One good way to wade out of the confusion is to imagine that C used a keyword (perhaps "nil", like Pascal) as a null pointer constant. The compiler could either turn "nil" into the appropriate type of null pointer when it could unambiguously determine that type from the source code, or complain when it could not. Now in fact, in C the keyword for a null pointer constant is not "nil" but "0", which works almost as well, except that an uncast "0" in a non-pointer context generates an
integer zero instead of an error message, and if that uncast 0 was supposed to be a null pointer constant, the code may not work.

12. I'm confused. I just can't understand all this null pointer stuff.
A: Here are two simple rules you can follow:
1. When you want a null pointer constant in source code, use "0" or "NULL".
2. If the usage of "0" or "NULL" is an argument in a function call, cast it to the pointer type expected by the function being called.

The rest of the discussion has to do with other people's misunderstandings, with the internal representation of null pointers (which you shouldn't need to know), and with the complexities of function prototypes. (Taking those complexities into account, we find that rule 2 is conservative, of course; but it doesn't hurt.)

13. Given all the confusion surrounding null pointers, wouldn't it be easier simply to require them to be represented internally by zeroes?
A: If for no other reason, doing so would be ill-advised because it would unnecessarily constrain implementations which would otherwise naturally represent null pointers by special, nonzero
bit patterns, particularly when those values would trigger automatic hardware traps for invalid accesses.
Besides, what would such a requirement really accomplish? Proper understanding of null pointers does not require knowledge of the internal representation, whether zero or nonzero. Assuming that null pointers are internally zero does not make any code easier to write (except for a certain ill-advised usage of calloc(); ). Known-zero internal pointers would not obviate casts in function calls, because the *size* of the pointer might still be different from that of an int. (If
"nil" were used to request null pointers, the urge to assume an internal zero representation would not even arise.)

14 Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types?
A: The Prime 50 series used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as
TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. Older, word-addressed Prime machines were also notorious for requiring
larger byte pointers (char *'s) than word pointers (int *'s).

The Eclipse MV series from Data General has three architecturally supported pointer formats (word, byte, and bit pointers), two of which are used by C compilers: byte pointers for char * and void *, and word pointers for everything else.
Some Honeywell-Bull mainframes use the bit pattern 06000 for (internal) null pointers.

The CDC Cyber 180 Series has 48-bit pointers consisting of a ring, segment, and offset. Most users (in ring 11) have null pointers of 0xB00000000000. It was common on old CDC ones- complement machines to use an all-one-bits word as a special flag for all kinds of data, including invalid addresses.

The old HP 3000 series uses a different addressing scheme for byte addresses than for word addresses; like several of the machines above it therefore uses different representations for
char * and void * pointers than for other pointers.

The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair (basically a nonexistent handle) as a C null
pointer.

Depending on the "memory model" in use, 8086-family processors (PC compatibles) may use 16-bit data pointers and 32-bit function pointers, or vice versa.

Some 64-bit Cray machines represent int * in the lower 48 bits of a word; char * additionally uses the upper 16 bits to indicate a byte address within a word.

15 What does a run-time "null pointer assignment" error mean?
How can I track it down?
A: This message, which typically occurs with MS-DOS compilers, means that you've written, via a null (perhaps because uninitialized) pointer, to an invalid location (probably offset 0 in the default data segment).
A debugger may let you set a data watchpoint on location 0. Alternatively, you could write a bit of code to stash away a copy of 20 or so bytes from location 0, and periodically check that the memory at location 0 hasn't changed. See also question 16.8.

IMP interview questions C language arrays pointers questions - 8

C computer language free download Arrays and Pointers used together questions and programs.

1. I had the definition char a[6] in one source file, and in another I declared extern char *a. Why didn't it work?
A: In one source file you defind an array of characters and in the other you declared a pointer to characters. The declaration extern char *a simply does not match the actual definition. The type pointer-to-type-T is not the same as array-of-type-T. Use extern char a[].

2. But I heard that char a[] was identical to char *a.
A: Not at all. (What you heard has to do with formal parameters to functions; see question 6.4.) Arrays are not pointers. The array declaration char a[6] requests that space for six characters be set aside, to be known by the name "a". That is, there is a location named "a" at which six characters can sit. The pointer declaration char *p, on the other hand, requests a
place which holds a pointer, to be known by the name "p". This pointer can point almost anywhere: to any char, or to any contiguous array of chars, or nowhere
As usual, a picture is worth a thousand words. The declarations
char a[] = "hello";
char *p = "world";
would initialize data structures which could be represented like
this:
+---+---+---+---+---+---+
a: h e l l o \0
+---+---+---+---+---+---+
+-----+ +---+---+---+---+---+---+
p: *======> w o r l d \0
+-----+ +---+---+---+---+---+---+

It is important to realize that a reference like x[3] generates different code depending on whether x is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location "a", move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p", fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In other words, a[3] is
three places past (the start of) the object *named* a, while p[3] is three places past the object *pointed to* by p. In the example above, both a[3] and p[3] happen to be the character
'l', but the compiler gets there differently. (The essential difference is that the values of an array like a and a pointer like p are computed differently *whenever* they appear in expressions, whether or not they are being subscripted, as explained further in the next question.)

4. So what is meant by the "equivalence of pointers and arrays" in C?
A: Much of the confusion surrounding arrays and pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are "equivalent" means neither that they are
identical nor even interchangeable. What it means is that array and pointer arithmetic is defined such that a pointer can be conveniently used to access an array or to simulate an array.
Specifically, the cornerstone of the equivalence is this key definition:
An lvalue of type array-of-T which appears in an expression decays (with three exceptions) into a
pointer to its first element; the type of the resultant pointer is pointer-to-T.

That is, whenever an array appears in an expression, the compiler implicitly generates a pointer to the array's first element, just as if the programmer had written &a[0]. (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character
array.)
As a consequence of this definition, the compiler doesn't apply the array subscripting operator [] that differently to arrays and pointers, after all. In an expression of the form a[i], the
array decays into a pointer, following the rule above, and is then subscripted just as would be a pointer variable in the expression p[i] (although the eventual memory accesses will be different, as explained in question 6.2). If you were to assign the array's address to the pointer:
p = a;
then p[3] and a[3] would access the same element.

5. Then why are array and pointer declarations interchangeable as function formal parameters?

A: It's supposed to be a convenience.
Since arrays decay immediately into pointers, an array is never actually passed to a function. Allowing pointer parameters to be declared as arrays is a simply a way of making it look as
though an array was being passed, perhaps because the parameter will be used within the function as if it were an array. Specifically, any parameter declarations which "look like"
arrays, e.g.
void f(char a[])
{ ... }
are treated by the compiler as if they were pointers, since that is what the function will receive if an array is passed:

void f(char *a)
{ ... }

This conversion holds only within function formal parameter declarations, nowhere else. If the conversion bothers you, avoid it; many programmers have concluded that the confusion it
causes outweighs the small advantage of having the declaration "look like" the call or the uses within the function.

6. How can an array be an lvalue, if you can't assign to it?
A: The ANSI C Standard defines a "modifiable lvalue," which an array is not.

7. Practically speaking, what is the difference between arrays and pointers?
A: Arrays automatically allocate space, but can't be relocated or resized. Pointers must be explicitly assigned to point to allocated space (perhaps using malloc), but can be reassigned
(i.e. pointed at different objects) at will, and have many other uses besides serving as the base of blocks of memory.
Due to the so-called equivalence of arrays and pointers (see question 6.3), arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array. . (Be careful with sizeof, though.)

8. Someone explained to me that arrays were really just constant pointers.
A: This is a bit of an oversimplification. An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer

9. I came across some "joke" code containing the "expression" 5["abcdef"] . How can this be legal C?

A: Yes, Virginia, array subscripting is commutative in C. This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for *any* two expressions a and e, as long as one of them is a pointer expression and one is integral. This unsuspected
commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest

10. Since array references decay into pointers, if arr is an array, what's the difference between arr and &arr?
A: The type.
In Standard C, &arr yields a pointer, of type pointer-to-array-of-T, to the entire array. (In pre-ANSI C, the & in &arr generally elicited a warning, and was generally ignored.) Under all C compilers, a simple reference (without an explicit &) to an array yields a pointer, of type pointer-to-T, to the array's first element.

11. How do I declare a pointer to an array?
A: Usually, you don't want to. When people speak casually of a pointer to an array, they usually mean a pointer to its first element.

Instead of a pointer to an array, consider using a pointer to one of the array's elements. Arrays of type T decay into pointers to type T, which is convenient; subscripting or incrementing the resultant pointer will access the individual members of the array. True pointers to arrays, when subscripted or incremented, step over entire arrays, and are generally useful only when operating on arrays of arrays, if at all.

If you really need to declare a pointer to an entire array, use something like "int (*ap)[N];" where N is the size of the array. If the size of the array is unknown, N can in principle be omitted, but the resulting type, "pointer to array of unknown size," is useless.

12. How can I set an array's size at run time? How can I avoid fixed-sized arrays?
A: The equivalence between arrays and pointers allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing
#include
int *dynarray;
dynarray = malloc(10 * sizeof(int));

(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the "array".

13. How can I declare local arrays of a size matching a passed-in array?
A: Until recently, you couldn't. Array dimensions in C traditionally had to be compile-time constants. C9X will introduce variable-length arrays (VLA's) which will solve this problem; local arrays may have sizes set by variables or other expressions, perhaps involving function parameters. (gcc has
provided parameterized arrays as an extension for some time.) If you can't use C9X or gcc, you'll have to use malloc(), and remember to call free() before the function returns.

14. How can I dynamically allocate a multidimensional array?
A: The traditional solution is to allocate an array of pointers, and then initialize each pointer to a dynamically-allocated "row." Here is a two-dimensional example:

#include ;
int **array1 = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(int));

(In real code, of course, all of malloc's return values would be checked.)

You can keep the array's contents contiguous, at the cost of making later reallocation of individual rows more difficult, with a bit of explicit pointer arithmetic:
int **array2 = malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int));
for(i = 1; i< nrows; i++)
array2[i] = array2[0] + i * ncolumns;

If the double indirection implied by the above schemes is for some reason unacceptable, you can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional
array:
int *array3 = malloc(nrows * ncolumns * sizeof(int));
However, you must now perform subscript calculations manually, accessing the i,jth element with array3[i * ncolumns + j]. (A macro could hide the explicit calculation, but invoking it would require parentheses and commas which wouldn't look exactly like multidimensional array syntax, and the macro would need access to at least one of the dimensions, as well.

Yet another option is to use pointers to arrays:
int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4));
but the syntax starts getting horrific and at most one dimension may be specified at run time.

With all of these techniques, you may of course need to remember to free the arrays (which may take several steps; ) when they are no longer needed, and you cannot necessarily intermix dynamically-allocated arrays with conventional, statically-allocated ones.

Finally, in C9X you can use a variable-length array.
All of these techniques can also be extended to three or more dimensions.

15. Here's a neat trick: if I write
int realarray[10];
int *array = &realarray[-1];
I can treat "array" as if it were a 1-based array. Why?

A: Although this technique is attractive (and was used in old editions of the book _Numerical Recipes in C_), it is not strictly conforming to the C Standard. Pointer arithmetic is defined only as long as the pointer points within the same allocated block of memory, or to the imaginary "terminating" element one past it; otherwise, the behavior is undefined, *even if the pointer is not dereferenced*. The code above could fail if, while subtracting the offset, an illegal address were generated (perhaps because the address tried to "wrap around" past the beginning of some memory segment).

16. My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer.
A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays (i.e. a two- dimensional array in C) decays into a pointer to an array, not a pointer to a pointer. Pointers to arrays can be confusing, and must be treated carefully;

If you are passing a two-dimensional array to a function:
int array[NROWS][NCOLUMNS];
f(array);

the function's declaration must match:

void f(int a[][NCOLUMNS])
{ ... }
or
void f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */
{ ... }
In the first declaration, the compiler performs the usual implicit parameter rewriting of "array of array" to "pointer to array" in the second form the pointer declaration is explicit. Since the called function does not allocate space for the array, it does not need to know the overall size, so the number of rows, NROWS, can be omitted. The width of the array is still important, so the column dimension
NCOLUMNS (and, for three- or more dimensional arrays, the intervening ones) must be retained.

If a function is already declared as accepting a pointer to a pointer, it is almost certainly meaningless to pass a two- dimensional array directly to it.

17. How do I write functions which accept two-dimensional arrays when the width is not known at compile time?
A: It's not always easy. One way is to pass in a pointer to the [0][0] element, along with the two dimensions, and simulate array subscripting "by hand":

void f2(int *aryp, int nrows, int ncolumns)
{ ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }

This function could be called with the array

f2(&array[0][0], NROWS, NCOLUMNS);

It must be noted, however, that a program which performs multidimensional array subscripting "by hand" in this way is not in strict conformance with the ANSI C Standard; according to an official interpretation, the behavior of accessing (&array[0][0])[x] is not defined for x >= NCOLUMNS.

C9X will allow variable-length arrays, and once compilers which accept C9X's extensions become widespread, this will probably become the preferred solution. (gcc has supported variable- sized arrays for some time.)

When you want to be able to use a function on multidimensional arrays of various sizes, one solution is to simulate all the arrays dynamically.

18. How can I use statically- and dynamically-allocated multidimensional arrays interchangeably when passing them to functions?

A: There is no single perfect method. Given the declarations

int array[NROWS][NCOLUMNS];
int **array1; /* ragged */
int **array2; /* contiguous */
int *array3; /* "flattened" */
int (*array4)[NCOLUMNS];

with the pointers initialized as in the code fragments in and functions declared as
void f1a(int a[][NCOLUMNS], int nrows, int ncolumns);
void f1b(int (*a)[NCOLUMNS], int nrows, int ncolumns);
void f2(int *aryp, int nrows, int ncolumns);
void f3(int **pp, int nrows, int ncolumns);
where f1a() and f1b() accept conventional two-dimensional arrays, f2() accepts a "flattened" two-dimensional array, and f3() accepts a pointer-to-pointer, simulated array the following calls should work as expected:

f1a(array, NROWS, NCOLUMNS);
f1b(array, NROWS, NCOLUMNS);
f1a(array4, nrows, NCOLUMNS);
f1b(array4, nrows, NCOLUMNS);
f2(&array[0][0], NROWS, NCOLUMNS);
f2(*array, NROWS, NCOLUMNS);
f2(*array2, nrows, ncolumns);
f2(array3, nrows, ncolumns);
f2(*array4, nrows, NCOLUMNS);
f3(array1, nrows, ncolumns);
f3(array2, nrows, ncolumns);

The following calls would probably work on most systems, but involve questionable casts, and work only if the dynamic ncolumns matches the static NCOLUMNS:

f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
f1a((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);
f1b((int (*)[NCOLUMNS])array3, nrows, ncolumns);

It must again be noted that passing &array[0][0] (or, equivalently, *array) to f2() is not strictly conforming;
If you can understand why all of the above calls work and are written as they are, and if you understand why the combinations that are not listed would not work, then you have a *very* good
understanding of arrays and pointers in C.

Rather than worrying about all of this, one approach to using multidimensional arrays of various sizes is to make them *all* dynamic. If there are no static multidimensional arrays -- if all arrays are allocated like array1 or array2 -- then all functions can be written like f3().

19. Why doesn't sizeof properly report the size of an array when the array is a parameter to a function?
A: The compiler pretends that the array parameter was declared as a pointer and sizeof reports the size of the pointer.

IMP interview questions C language Questions and answers - 9

Memory Allocation Strategy and c language Programs

1. Why doesn't this fragment work?
char *answer;
printf("Type something:\n");
gets(answer);
printf("You typed \"%s\"\n", answer);

A: The pointer variable answer, which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where
the pointer answer points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer starts out as a null pointer.

The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation:

#include
#include

char answer[100], *p;
printf("Type something:\n");
fgets(answer, sizeof answer, stdin);
if((p = strchr(answer, '\n')) != NULL)
*p = '\0';
printf("You typed \"%s\"\n", answer);

This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer.

2. I can't get strcat() to work. I tried
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
but I got strange results.Why ?

A: As in question 1 above, the main problem here is that spacefor the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of strings, this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by
calling malloc().

strcat() performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array:

char s1[20] = "Hello, ";

Since strcat() returns the value of its first argument (s1, in this case), the variable s3 is superfluous; after the call to strcat(), s1 contains the result.

The original call to strcat() in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all.

3. But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things?
A: In general, when using pointers you *always* have to consider memory allocation, if only to make sure that the compiler is doing it for you. If a library function's documentation does not explicitly mention allocation, it is usually the caller's problem.

The Synopsis section at the top of a Unix-style man page or in the ANSI C standard can be misleading. The code fragments presented there are closer to the function definitions used by
an implementor than the invocations used by the caller. In particular, many functions which accept pointers (e.g. to structures or strings) are usually called with a pointer to some object (a structure, or an array ) which the caller has allocated. Other common examples are time() and stat().

4. I just tried the code
char *p;
strcpy(p, "abc");
and it worked. How? Why didn't it crash?
A: You got lucky, I guess. The memory pointed to by the unitialized pointer p happened to be writable by you, and apparently was not already in use for anything vital.

5.How much memory does a pointer variable allocate?
A: That's a pretty misleading question. When you declare a pointer variable, as in

char *p;

you (or, more properly, the compiler) have allocated only enough memory to hold the pointer itself; that is, in this case you have allocated sizeof(char *) bytes of memory. But you have not yet allocated *any* memory for the pointer to point to.

6.I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.
A: Make sure that the pointed-to memory is properly allocated. For example, make sure you have *not* done something like

char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}

One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as

static char retbuf[20];

7. So what's the right way to return a string or other aggregate?
A: The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc(), but *not* to a local (automatic) array.

8. Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()?
A: Have you #include, or otherwise arranged for malloc() to be declared properly.

9. Why does some code carefully cast the values returned by malloc to the pointer type being allocated?
A: Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types.

Under ANSI/ISO Standard C, these casts are no longer necessary, and in fact modern practice discourages them, since they can camouflage important warnings which would otherwise be generated if malloc() happened not to be declared correctly; (However, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.)

10. I see code like
char *p = malloc(strlen(s) + 1);
strcpy(p, s);
Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
A: It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and in some circumstances may help by introducing a size_t into the expression.)

11. I've heard that some operating systems don't actually allocate memory until the program tries to use it. Is this legal?
A: It's hard to say. The Standard doesn't say that systems can act this way, but it doesn't explicitly say that they can't, either.

12. I'm allocating a large array for some numeric work, using the line
double *array = malloc(300 * 300 * sizeof(double));
malloc() isn't returning null, but the program is acting strangely, as if it's overwriting memory, or malloc() isn't allocating as much as I asked for, or something.
A: Notice that 300 x 300 is 90,000, which will not fit in a 16-bit int, even before you multiply it by sizeof(double). If you need to allocate this much memory, you'll have to be careful. If size_t (the type accepted by malloc()) is a 32-bit type on your machine, but int is 16 bits, you might be able to get away with writing 300 * (300 * sizeof(double)). Otherwise, you'll have to break your data structure up into smaller chunks, or use a 32-bit machine or compiler, or use some nonstandard memory allocation functions.

13.I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K or so?
A: Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency, especially under MS-DOS.

14. My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. Is there a bug in malloc()?
A: It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed
region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. Other problems may involve using pointers to memory that has been freed, freeing pointers twice, freeing pointers not obtained from malloc, or trying to realloc a null pointer

15. You can't use dynamically-allocated memory after you free it, can you?
A: No. Some early documentation for malloc() stated that the contents of freed memory were "left undisturbed," but this ill- advised guarantee was never universal and is not required by the C Standard.

Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list:

struct list *listp, *nextp;
for(listp = base; listp != NULL; listp = nextp) {
nextp = listp->next;
free(listp);
}

and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer.

16. Why isn't a pointer null after calling free()? How unsafe is it to use (assign, compare) a pointer value after it's been freed?
A: When you call free(), the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller probably remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments.

A pointer value which has been freed is, strictly speaking, invalid, and *any* use of it, even if is not dereferenced, can theoretically lead to trouble, though as a quality of implementation issue, most implementations will probably not go out of their way to generate exceptions for innocuous uses of
invalid pointers.

17.When I call malloc() to allocate memory for a pointer which is local to a function, do I have to explicitly free() it?
A: Yes. Remember that a pointer is different from what it points to. Local variables are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, *not* what it points to. Memory allocated with malloc() always persists until you explicitly free it. In general, for every call to malloc(), there should be a corresponding call to free().

18. I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I also have to free each subsidiary pointer?
A: Yes. In general, you must arrange that each pointer returned from malloc() be individually passed to free(), exactly once (if it is freed at all). A good rule of thumb is that for each call to malloc() in a program, you should be able to point at the call to free() which frees the memory allocated by that malloc() call.

19. Must I free allocated memory before the program exits?
A: You shouldn't have to. A real operating system definitively reclaims all memory and other resources when a program exits. Nevertheless, some personal computers are said not to reliably
recover memory, and all that can be inferred from the ANSI/ISO C Standard is that this is a "quality of implementation issue."

20. I have a program which mallocs and later frees a lot of memory, but I can see from the operating system that memory usage doesn't actually go back down.
A: Most implementations of malloc/free do not return freed memory to the operating system, but merely make it available for future malloc() calls within the same program.

21. How does free() know how many bytes to free?
A: The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing.

22. So can I query the malloc package to find out how big an allocated block is?
A: Unfortunately, there is no standard or portable way.

23. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to?
A: ANSI C sanctions this usage (and the related realloc(..., 0), which frees), although several earlier implementations do not support it, so it may not be fully portable. Passing an initially-null pointer to realloc() can make it easier to write a self-starting incremental allocation algorithm.

24. What's the difference between calloc() and malloc()? Is it safe to take advantage of calloc's zero-filling? Does free() work on memory allocated with calloc(), or do you need a cfree()?
A: calloc(m, n) is essentially equivalent to

p = malloc(m * n);
memset(p, 0, m * n);

The zero fill is all-bits-zero, and does *not* therefore guarantee useful null pointer values (see section 5 of this list) or floating-point zero values. free() is properly used to free the memory allocated by calloc().

25. What is alloca() and why is its use discouraged?
A: alloca() allocates memory which is automatically freed when the function which called alloca() returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context.

alloca() cannot be written portably, and is difficult to implement on machines without a conventional stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin).

For these reasons, alloca() is not Standard and cannot be used in programs which must be widely portable, no matter how useful it might be.

Tuesday, August 5, 2008

C language Technical Interview Questions and Project Notes / topics - 10 IMP interview questions

Characters and Strings

1. Why doesn't
strcat(string, '!');
work?
A: There is a very real difference between characters and strings, and strcat() concatenates *strings*.
Characters in C are represented by small integers corresponding to their character set values.
Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append
a ! to a string, use
strcat(string, "!");

2. I'm checking a string to see if it matches a particular value. Why isn't this code working?
char *string;
...
if(string == "value") {
/* string matches "value" */
...
}
A: Strings in C are represented as arrays of characters, and C never manipulates (assigns, compares, etc.) arrays as a whole. The == operator in the code fragment above compares two pointers -- the value of the pointer variable string and a pointer to the string literal "value" -- to see if they are equal, that is, if they point to the same place. They probably don't, so the comparison never succeeds.

To compare two strings, you generally use the library function strcmp():

if(strcmp(string, "value") == 0) {
/* string matches "value" */
...
}

3. If I can say
char a[] = "Hello, world!";
why can't I say
char a[14];
a = "Hello, world!";
A: Strings are arrays, and you can't assign arrays directly. Use strcpy() instead:
strcpy(a, "Hello, world!");

4. How can I get the numeric (character set) value corresponding to a character, or vice versa?
A: In C, characters are represented by small integers corresponding to their values (in the machine's character set), so you don't need a conversion function: if you have the character, you have its value.

5. I think something's wrong with my compiler: I just noticed that sizeof('a') is 2, not 1 (i.e. not sizeof(char)).
A: Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).

Boolean Expressions and Variables

1. What is the right type to use for Boolean values in C? Why isn't it a standard type? Should I use #defines or enums for the true and false values?
A: C does not provide a standard Boolean type, in part because picking one involves a space/time tradeoff which can best be decided by the programmer. (Using an int may be faster, while using char may save data space. Smaller types may make the generated code bigger or slower, though, if they require lots of conversions to and from int.)

The choice between #defines and enumeration constants for the true/false values is arbitrary and not terribly interesting . Use any of
#define TRUE 1 #define YES 1
#define FALSE 0 #define NO 0
enum bool {false, true}; enum bool {no, yes};
or use raw 1 and 0, as long as you are consistent within one program or project. (An enumeration may be preferable if your debugger shows the names of enumeration constants when examining
variables.)
Some people prefer variants like
#define TRUE (1==1)
#define FALSE (!TRUE)
or define "helper" macros such as
#define Istrue(e) ((e) != 0)
These don't buy anything.

2. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is considered "true" in C? What if a built-in logical or relational operator "returns" something other than 1?
A: It is true (sic) that any nonzero value is considered true in C, but this applies only "on input", i.e. where a Boolean value is expected. When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0. Therefore, the test
if((a == b) == TRUE)
would work as expected (as long as TRUE is 1), but it is obviously silly. In fact, explicit tests against TRUE and FALSE are generally inappropriate, because some library functions (notably isupper(), isalpha(), etc.) return, on success, a nonzero value which is not necessarily 1.
(Besides, if you believe that "if((a == b) == TRUE)" is an improvement over "if(a == b)", why stop there? Why not use "if(((a == b) == TRUE) == TRUE)"?) A good rule of thumb is to use TRUE and FALSE (or the like) only for assignment to a Boolean variable or function parameter, or as the return
value from a Boolean function, but never in a comparison.
The preprocessor macros TRUE and FALSE (and, of course, NULL) are used for code readability, not because the underlying values might ever change.
Although the use of macros like TRUE and FALSE (or YES and NO) seems clearer, Boolean values and definitions can be sufficiently confusing in C that some programmers feel that TRUE and FALSE macros only compound the confusion, and prefer to use raw 1 and 0 instead.

C language latest and recent interview questions for 2008 asked in latest placement papers of leading companies in India, USA, etc. Project notes for students /college admission interviews, important basic free download programs with detailed answers and solutions for freshers and walkins for all university bca, btech, engineering, computer applications, developers jobs, etc.

AddThis Social Bookmark Button

Posted by mani at 6:50 PM 0 comments

Labels: C language latest technical interview questions and answers

C language Questions and answers - 9

Memory Allocation Strategy and c language Programs

1. Why doesn't this fragment work?
char *answer;
printf("Type something:\n");
gets(answer);
printf("You typed \"%s\"\n", answer);

A: The pointer variable answer, which is handed to gets() as the location into which the response should be stored, has not been set to point to any valid storage. That is, we cannot say where
the pointer answer points. (Since local variables are not initialized, and typically contain garbage, it is not even guaranteed that answer starts out as a null pointer.

The simplest way to correct the question-asking program is to use a local array, instead of a pointer, and let the compiler worry about allocation:

#include
#include

char answer[100], *p;
printf("Type something:\n");
fgets(answer, sizeof answer, stdin);
if((p = strchr(answer, '\n')) != NULL)
*p = '\0';
printf("You typed \"%s\"\n", answer);

This example also uses fgets() instead of gets(), so that the end of the array cannot be overwritten. Unfortunately for this example, fgets() does not automatically delete the trailing \n, as gets() would.) It would also be possible to use malloc() to allocate the answer buffer.

2. I can't get strcat() to work. I tried
char *s1 = "Hello, ";
char *s2 = "world!";
char *s3 = strcat(s1, s2);
but I got strange results.Why ?

A: As in question 1 above, the main problem here is that spacefor the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of strings, this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by
calling malloc().

strcat() performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array:

char s1[20] = "Hello, ";

Since strcat() returns the value of its first argument (s1, in this case), the variable s3 is superfluous; after the call to strcat(), s1 contains the result.

The original call to strcat() in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all.

3. But the man page for strcat() says that it takes two char *'s as arguments. How am I supposed to know to allocate things?
A: In general, when using pointers you *always* have to consider memory allocation, if only to make sure that the compiler is doing it for you. If a library function's documentation does not explicitly mention allocation, it is usually the caller's problem.

The Synopsis section at the top of a Unix-style man page or in the ANSI C standard can be misleading. The code fragments presented there are closer to the function definitions used by
an implementor than the invocations used by the caller. In particular, many functions which accept pointers (e.g. to structures or strings) are usually called with a pointer to some object (a structure, or an array ) which the caller has allocated. Other common examples are time() and stat().

4. I just tried the code
char *p;
strcpy(p, "abc");
and it worked. How? Why didn't it crash?
A: You got lucky, I guess. The memory pointed to by the unitialized pointer p happened to be writable by you, and apparently was not already in use for anything vital.

5.How much memory does a pointer variable allocate?
A: That's a pretty misleading question. When you declare a pointer variable, as in

char *p;

you (or, more properly, the compiler) have allocated only enough memory to hold the pointer itself; that is, in this case you have allocated sizeof(char *) bytes of memory. But you have not yet allocated *any* memory for the pointer to point to.

6.I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.
A: Make sure that the pointed-to memory is properly allocated. For example, make sure you have *not* done something like

char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}

One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as

static char retbuf[20];

7. So what's the right way to return a string or other aggregate?
A: The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc(), but *not* to a local (automatic) array.

8. Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()?
A: Have you #include, or otherwise arranged for malloc() to be declared properly.

9. Why does some code carefully cast the values returned by malloc to the pointer type being allocated?
A: Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types.

Under ANSI/ISO Standard C, these casts are no longer necessary, and in fact modern practice discourages them, since they can camouflage important warnings which would otherwise be generated if malloc() happened not to be declared correctly; (However, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.)

10. I see code like
char *p = malloc(strlen(s) + 1);
strcpy(p, s);
Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
A: It's never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesn't hurt, and in some circumstances may help by introducing a size_t into the expression.)

11. I've heard that some operating systems don't actually allocate memory until the program tries to use it. Is this legal?
A: It's hard to say. The Standard doesn't say that systems can act this way, but it doesn't explicitly say that they can't, either.

12. I'm allocating a large array for some numeric work, using the line
double *array = malloc(300 * 300 * sizeof(double));
malloc() isn't returning null, but the program is acting strangely, as if it's overwriting memory, or malloc() isn't allocating as much as I asked for, or something.
A: Notice that 300 x 300 is 90,000, which will not fit in a 16-bit int, even before you multiply it by sizeof(double). If you need to allocate this much memory, you'll have to be careful. If size_t (the type accepted by malloc()) is a 32-bit type on your machine, but int is 16 bits, you might be able to get away with writing 300 * (300 * sizeof(double)). Otherwise, you'll have to break your data structure up into smaller chunks, or use a 32-bit machine or compiler, or use some nonstandard memory allocation functions.

13.I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K or so?
A: Under the segmented architecture of PC compatibles, it can be difficult to use more than 640K with any degree of transparency, especially under MS-DOS.

14. My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. Is there a bug in malloc()?
A: It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed
region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. Other problems may involve using pointers to memory that has been freed, freeing pointers twice, freeing pointers not obtained from malloc, or trying to realloc a null pointer

15. You can't use dynamically-allocated memory after you free it, can you?
A: No. Some early documentation for malloc() stated that the contents of freed memory were "left undisturbed," but this ill- advised guarantee was never universal and is not required by the C Standard.

Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list:

struct list *listp, *nextp;
for(listp = base; listp != NULL; listp = nextp) {
nextp = listp->next;
free(listp);
}

and notice what would happen if the more-obvious loop iteration expression listp = listp->next were used, without the temporary nextp pointer.

16. Why isn't a pointer null after calling free()? How unsafe is it to use (assign, compare) a pointer value after it's been freed?
A: When you call free(), the memory pointed to by the passed pointer is freed, but the value of the pointer in the caller probably remains unchanged, because C's pass-by-value semantics mean that called functions never permanently change the values of their arguments.

A pointer value which has been freed is, strictly speaking, invalid, and *any* use of it, even if is not dereferenced, can theoretically lead to trouble, though as a quality of implementation issue, most implementations will probably not go out of their way to generate exceptions for innocuous uses of
invalid pointers.

17.When I call malloc() to allocate memory for a pointer which is local to a function, do I have to explicitly free() it?
A: Yes. Remember that a pointer is different from what it points to. Local variables are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, *not* what it points to. Memory allocated with malloc() always persists until you explicitly free it. In general, for every call to malloc(), there should be a corresponding call to free().

18. I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I also have to free each subsidiary pointer?
A: Yes. In general, you must arrange that each pointer returned from malloc() be individually passed to free(), exactly once (if it is freed at all). A good rule of thumb is that for each call to malloc() in a program, you should be able to point at the call to free() which frees the memory allocated by that malloc() call.

19. Must I free allocated memory before the program exits?
A: You shouldn't have to. A real operating system definitively reclaims all memory and other resources when a program exits. Nevertheless, some personal computers are said not to reliably
recover memory, and all that can be inferred from the ANSI/ISO C Standard is that this is a "quality of implementation issue."

20. I have a program which mallocs and later frees a lot of memory, but I can see from the operating system that memory usage doesn't actually go back down.
A: Most implementations of malloc/free do not return freed memory to the operating system, but merely make it available for future malloc() calls within the same program.

21. How does free() know how many bytes to free?
A: The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing.

22. So can I query the malloc package to find out how big an allocated block is?
A: Unfortunately, there is no standard or portable way.

23. Is it legal to pass a null pointer as the first argument to realloc()? Why would you want to?
A: ANSI C sanctions this usage (and the related realloc(..., 0), which frees), although several earlier implementations do not support it, so it may not be fully portable. Passing an initially-null pointer to realloc() can make it easier to write a self-starting incremental allocation algorithm.

24. What's the difference between calloc() and malloc()? Is it safe to take advantage of calloc's zero-filling? Does free() work on memory allocated with calloc(), or do you need a cfree()?
A: calloc(m, n) is essentially equivalent to

p = malloc(m * n);
memset(p, 0, m * n);

The zero fill is all-bits-zero, and does *not* therefore guarantee useful null pointer values (see section 5 of this list) or floating-point zero values. free() is properly used to free the memory allocated by calloc().

25. What is alloca() and why is its use discouraged?
A: alloca() allocates memory which is automatically freed when the function which called alloca() returns. That is, memory allocated with alloca is local to a particular function's "stack frame" or context.

alloca() cannot be written portably, and is difficult to implement on machines without a conventional stack. Its use is problematical (and the obvious implementation on a stack-based machine fails) when its return value is passed directly to another function, as in fgets(alloca(100), 100, stdin).

For these reasons, alloca() is not Standard and cannot be used in programs which must be widely portable, no matter how useful it might be.