-2

I have a string in C named buff. It is defined as char *buf = malloc(size);. I'm new to C but think this means that the values of the bytes of data allocated is stored in buf. All code is below

When I run sizeof(buf) it gives a size of 8 despite it clearly being full of more than 8 characters. I also have problems with taking the returned pointer and putting it through strlen which gives a value double what I expect.

This is a function to create an array of characaters read from a file.

The comments below used an example file of input.txt with contents ()()(()()(

const char* readFile() 
{
    FILE* fp;
    int c;
    int nch = 0;
    int size = 100;
    fp = fopen("./input.txt","r");
    //allocates a block of 100 bytes and sets buf as the values associated with those values
    char *buf = malloc(size);
    if(buf == NULL)
        {
        fprintf(stderr, "out of memory\n");
        return NULL;
        }
    while((c = fgetc(fp)) != EOF) //sets c to the next character of fp and checks it isn't the end
        {
        if(nch >= size-1) //size-1 as need an extra character for '\0'
            {
            /* time to make it bigger */
            //printf("size: %d \n",size);
            size += 50;
            buf = realloc(buf, size);
            //size_t n = arraySize(buf);
            //printf("buf is %zu chars long \n",n);
            if(buf == NULL)
                {
                fprintf(stderr, "out of memory\n");
                return NULL;
                }
            }

        buf[nch++] = c; //steps nch and stores c
        }
    buf[nch++] = '\0';
    printf("size: %d\n",size); //output 100

    printf("nch: %d\n",nch); //output 11
    buf = realloc(buf, nch); //sets the buf to the size it actually needs

    printf("buf is %d long\n",sizeof(buf)); //outputs sizeof(buf) as 8.
    printf("buf[0] is %d long\n",sizeof(buf[0])); //outputs sizeof(buf[0]) as 1.
    printf("\"%s\"\n", buf); //shows it reads the file properly. outputs "0123456789"
    return buf;
}

int main(){
    const char *fileContents = readFile(); //defines it as the address of the first character
    printf("\"%s\"\n", fileContents); //outputs the file contents correctly
    int count = 0;
    printf("strlen: %d\n",strlen(fileContents)); //outputs 10
    int i, lenStr = strlen(fileContents);
    for(i = 0; i < lenStr; i++){ 
        char c = *(fileContents+i); //sets character at position i to c
        printf("character: %c  i: %d\n",c,i); //outputs expected value
        switch(c){ //this works sort of and correctly identifies values
        case '(':
            printf("increasing count\n");
            count++;
            break;
        case ')':
            printf("decreasing count\n");
            count--;
            break;
        default:
            printf("things are going wrong \n");
            break;
        }
        fileContents++;
    }
    printf("go up %d floors",count);
    getchar();
    return 0;
}

output of for loop with select statment

character: (  i: 0
increasing count
character: (  i: 1
increasing count
character: (  i: 2
increasing count
character: )  i: 3
decreasing count
character: )  i: 4
decreasing count
character:    i: 5
things are going wrong
character:    i: 6
things are going wrong
character:    i: 7
things are going wrong
character: e  i: 8
things are going wrong
character: s  i: 9
things are going wrong

For some reason the output is in the wrong order before it starts breaking.

It feels like the problem is I don't fully understand pointers. I'm just not sure how I am misunderstanding them.

charlie scott
  • 136
  • 1
  • 9
  • 7
    `sizeof(buf)` is size of _pointer_ – Paul Ogilvie Apr 15 '21 at 16:01
  • 1
    The size of your `buf` buffer is `size` (that is the value you passed to `malloc`), `sizeof(buf)` is the size of a pointer (usually 4 on a 32 bit platform and 8 on a 64 bit platform).There is no way to determine the size of a buffer. – Jabberwocky Apr 15 '21 at 16:04
  • 4
    For the future, construct a [mre]. This simple main would have been enough. `int main(void) { char *buf = malloc(1000); printf("%zu\n", sizeof buf); }` – klutt Apr 15 '21 at 16:05
  • I voted for reopen seeing `fileContents++;`, but I agree that this question is duplicate for the `sizeof(buf)` part. – MikeCAT Apr 15 '21 at 16:22

1 Answers1

0

The main problem is that you are doing fileContents++;. This adds one to the pointer fileContents, sliding the place to view.

You should remove this so that the characters will be processed one-by-one thanks to i++ in the for loop.

Another problem is that you are invoking undefined behavior by passing data having wrong type to printf. sizeof operator and strlen returns size_t, but %d expects int. The correct format specifier to print size_t is %zu.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70