top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Is it necessary to cast the result of malloc?

+2 votes
268 views
Is it necessary to cast the result of malloc?
posted Apr 7, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

In successful case, malloc returns valid void pointer of allocated memory block and NULL when memory allocation gets failed. As per memory usage requirement, user should typecast allocated memory chunk otherwise none of the operations like increments, decrements, de-referencing of void pointer etc can be performed by using void pointer type.

answer Apr 8, 2015 by Vimal Kumar Mishra
Similar Questions
+4 votes

I believe option 1 is more correct, dont know why?

1) int *p = malloc(sizeof(int)*l);
2) int *p = (int *)malloc(sizeof(int)*l);
+1 vote

Crazy Zak has designed the below steps which can be applied on any given string (sentence) to produce a number.
In each word, find the Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word.
Concatenate the sums of each word to form the result.
If the given string is “WORLD WIDE WEB”
In each word, find the Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word.
WORLD = [W-D]+[O-L]+[R] = [23-4]+[15-12]+[18] = [19]+[3]+[18] = [40]

WIDE = [W-E]+[I-D] = [23-5]+[9-4] = [18]+[5] = [23]

WEB = [W-B]+[E] = [23-2]+[5] = [21]+[5] = [26]
Concatenate the sums of each word to form the result
[40] [23] [26]
[402326]

The answer (output) should be the number 402326.

NOTE1: The value of each letter is its position in the English alphabet system i.e. a=A=1, b=B=2, c=C=3, and so on till z=Z=26.

So, the result will be the same for “WORLD WIDE WEB” or “World Wide Web” or “world wide web” or any other combination of uppercase and lowercase letters.

In Step1, after subtracting the alphabets, we should use the absolute values for calculating the sum. For instance, in the below example, both [H-O] and [E-L] result in negative number -7, but the positive number 7 (absolute value of -7) is used for calculating the sum of the differences.
Hello = [H-O]+[E-L]+[L] = [8-15]+[5-12]+[12] = [7]+[7]+[12] = [26]

Assumptions: The given string (sentence) will contain only alphabet characters and there will be only one space character between any two consecutive words.
You are expected to help Zak, by writing a function that takes a string (sentence) as input, performs the above mentioned processing on the sentence and returns the result (number).

...