Search code examples
carraysrealloc

realloc not changíng size of array


Possible Duplicate:
Realloc is not resizing array of pointers

Can anyone tell me where my mistake is? this function should make an array of the characters supplied from stdin. I read some related questions but it was too complicated for me to understand.

char *readChar(void)
{
    int c;
    int len = 0;
    char* parr = malloc(sizeof(char));

    while((c = getchar()) != EOF)
    {
        ++len;
        int size = sizeof(char)*len;
        parr = (char *) realloc(parr,size);
        *(parr+size-1) = (char) c;
        printf("Done! Size should be: %dB, but real size is %dB\n",size,sizeof(parr));
    }

    return parr;
}

Output:

Done! Size should be: 1B, but real size is 8B Done! Size should be: 2B, but real size is 8B Done! Size should be: 3B, but real size is 8B Done! Size should be: 4B, but real size is 8B


Solution

  • The mistake is that sizeof() won't tell you the number of bytes you allocated. It tells you the size of the char *

    Sounds like what you wanted was to verify that you allocated the correct amount of memory. sizeof() won't give you that information. It's in the low level details at this point, you need to do something OS dependent to try and find that information. (ex. in the Linux kernel if you kmalloc() memory you can use ksize() to find out exactly how many bytes you got)