-1

For the following C code, I expect the last printf to print "10,10" when I input only one character. Instead it prints "10,8". Why is input only 8 bytes when I malloc 10 bytes?

char* input;
unsigned long inputLen = 10;

input = (char*) malloc(10 * sizeof(char));

printf("Input: ");
getline(&input,&inputLen,stdin);
printf("%lu,%d",inputLen,sizeof(input));
DowntownDev
  • 842
  • 10
  • 15
  • 2
    It is bad to cast malloc - see http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Ed Heal Jan 22 '17 at 23:37
  • 3
    `sizeof(char)` - this is always 1 – Ed Heal Jan 22 '17 at 23:38
  • 1
    The `getline()` function reports how many characters were read in its return value. You should use that rather than anything else to tell how long the input is. Using `strlen()` will usually give the same answer, but a user can enter null bytes in the input stream (Control-@ usually) and then `strlen()` gives a shorter answer. Note that if the user types more than 9 characters (including the newline), then the value in `inputLen` could be much larger. Also, the second argument to `getline()` should be `size_t *`; that isn't necessarily the same as `unsigned long`. – Jonathan Leffler Jan 22 '17 at 23:41
  • For purposes of the question, you could simplify your code to `printf("%d", sizeof(char*));`. – David Schwartz Jan 22 '17 at 23:41

3 Answers3

5

sizeof(input) returns the size of the pointer input, which is 8 bytes.

Via the C FAQ:

Q: Why doesn't sizeof tell me the size of the block of memory pointed to by a pointer?

A: sizeof tells you the size of the pointer. There is no portable way to find out the size of a malloc'ed block. (Remember, too, that sizeof operates at compile time, and see also question 7.27.)

If you want to keep track of the capacity of input, you need to use a separate variable, or declare input on the stack as an array, and divide the size of the array by the size of an individual element of the array. It's almost always easier just to preserve the capacity as a separate variable.

Community
  • 1
  • 1
Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
3

Why is input only 8 bytes when I malloc 10 bytes?

Because input is a pointer and pointers are 8 bytes on your platform. The sizeof function just tells you the size of the type, determined at compile time.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

It's because input is a char*. You should consider using strlen provided you null terminate it.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445