-2

Alright so i have my array:

unsiged int *arr = (unsigned int*)malloc(200 * sizeof(unsigned int));

Declared like this, and i have wrote a loop that loops through each element of the array and calls a function with the element as its argument, which looks like this:

for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
    sprintf(buffer, "/proc/%zu/cmdline", arr[i]);
    printf("/proc/%x/cmdline", arr[0]);
    printf("/proc/%zu/cmdline", arr[i]);
    checkIfRunning(buffer);
}

the checkIfRunning function contains:

void checkIfRunning(char *filepath) {
    FILE *fh;
    char buf[500];
    fh = fopen(filepath, "r");

   if (!fh)
       exit(1);

My code always exits at exit(1), i get the following (wrong) outputs from both the printf statements:

/proc/bbb07a63/cmdline
/proc/3148905059/cmdline

What am i doing wrong

Please note that i am new to c and i'm sorry if newbie question, also note that the output of printf is different each time, which i assume means its garbage.

john doe
  • 27
  • 3

2 Answers2

3

For an unsigned int *arr, expression sizeof(arr) is the size of a pointer value (e.g. 4 bytes on a 32 bit system), not the "length" of something this pointer points to. This is different from a declaration like unsigned int arr[100], where sizeof(arr) would give you 100*sizeof(unsigned int). You probably took over the pattern sizeof(arr) / sizeof(arr[0]) from an array declaration like unsigned int[100], yet this cannot be used for dynamically allocated memory. So you'd rather write for (size_t i = 0; i < 200; i++), or write #define ARRSIZE 200 and use ARRSIZE then for the malloc and for the loop.

Second, as mentioned by GrahamS, you do not show any code initialising the memory. If there isn't such initialisation, the behaviour of your program is undefined.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

You allocated the memory for the array, but you haven't set the contents of that memory to anything. So your array is just filled with random garbage.

GrahamS
  • 9,980
  • 9
  • 49
  • 63