Jim's
Tutorials

Spring 2018
course
site

C

Feb 1

Snow!

We continued the discussion of pointers and memory and sizeof().

You need to be careful with sizeof() - for memory allocated with malloc , it doesn't know the size of the array.

See the attached stuff.c where we were looking at some of this stuff.

In this case, sizeof(a) does give the total number of bytes that a points at, because when we declared it, the compiler knows at compile time that it's a pointer to 9 integers, which takes 9*4=36 bytes of space.

But sizeof(b) just returns the space needed to store a pointer. The declaration of b is that its an (int*) which is a pointer to an int, and storing a pointer takes 8 bytes (on a 64bit computer).

So you cannot use sizeof to figure out how many numbers you can store as b[0], b[1], b[2], ... .

softmaple:Desktop mahoney$ make stuff
cc     stuff.c   -o stuff
softmaple:Desktop mahoney$ ./stuff 
-- stuff --
 a = 0x10d341020 
 &a[0] = 0x10d341020 
 a[0] = 1 
 sizeof(int) = 4 
 &a[1] = 0x10d341024 
 sizeof(a) = 36 
 sizeof(a[0]) = 4 
 sizeof(b) = 8 
 sizeof(b[0]) = 4 
softmaple:Desktop mahoney$ 
/*  stuff.c
 *
 */

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

#define MAX_SIZE 100

int a[] = {1,2,3,4,5,6,7,8,9};

char name[256] = "George Martin";

int c[MAX_SIZE];

int main(){

  int* b = malloc(100*sizeof(int));               // space for 100 integers

  char* inputbuffer;

  inputbuffer = malloc(1000*sizeof(char));  // space for 1000 characters

  printf("-- stuff --\n");

  printf(" a = %p \n", a);
  printf(" &a[0] = %p \n", &a[0]);
  printf(" a[0] = %i \n", a[0]);
  printf(" sizeof(int) = %lu \n", sizeof(int));
  printf(" &a[1] = %p \n", &a[1]);
  printf(" sizeof(a) = %lu \n", sizeof(a));
  printf(" sizeof(a[0]) = %lu \n", sizeof(a[0]));

  b[0] = 10;
  b[20] = 20;
  printf(" sizeof(b) = %lu \n", sizeof(b));
  printf(" sizeof(b[0]) = %lu \n", sizeof(b[0]));

  return 0;
}
https://cs.marlboro.college /cours /spring2018 /jims_tutorials /web_tech /c_feb1
last modified Sat December 21 2024 5:57 pm

attachments [paper clip]

  last modified size
TXT stuff.c Sat Dec 21 2024 05:57 pm 790B