-5

I try to dynamically allocate memory to a string but when I print out the size it shows 4 instead of the (11+1) bytes that should be allocated. Why does this happen? The string prints out just fine.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
char c, *string;
int i=0, a=1;

printf("\nEnter the string : ");

string = (char *) malloc (sizeof(char));
while(c != '\n'){
    c = getchar();

    string = (char *) realloc (string, sizeof(char) * a);

    string[i] = c;

    a++, i++;
}
string[i] = '\0';

puts(string);

printf("\n%d", sizeof(string));

}

Input  : Sample Text
Output : 
    Sample Text
    4
Akash Aaron
  • 116
  • 1
  • 7
  • 2
    use `strlen(string)` instead of `sizeof(string)`, the latter gives the memory required to hold the *pointer to char*. Also, the proper format specifier for the number returned from `strlen` or given by `sizeof` is `%zu`. – Antti Haapala -- Слава Україні Feb 26 '17 at 11:41
  • 1
    A few things: First please read [this discussion about casting `malloc` (and friends)](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Secondly, When using [`realloc`](http://en.cppreference.com/w/c/memory/realloc) don't assign directly back to the pointer you pass to the function, think about what happens if [`realloc`](http://en.cppreference.com/w/c/memory/realloc) returns a null pointer. Thirdly, you don't allocate space for the terminator. Fourthly, you overwrite the last character with the terminator. – Some programmer dude Feb 26 '17 at 11:45
  • Bug: `string[i] = '\0';` however `string+i` doesn't exist (there is no storage for it allocated). – Paul Ogilvie Feb 26 '17 at 12:00

2 Answers2

0

sizeof is giving you the size of char pointer which is 4 on your platform.

Jubin Chheda
  • 534
  • 4
  • 11
0

The sizeof operator returns the "size" of the variable, which in this case is a pointer. On 32-bit systems a pointer is 4 bytes so this what is printed. You want to use the strlen(char*) function, which looks at the memory that contains the string the pointer goes to. This function will count how many bytes it sees until a final 0 terminator byte.