dodo dodo - 1 month ago 19
C Question

C Segmentation Fault within Kali Linux VM

I am trying to create a C program in a Linux VM that uses a char array. I found that every time I try to do anything to the array, e.g.

sizeof()
, I get a segmentation fault. I wrote a test program that just made an array and got
sizeof()
as a test, and sure enough I get the same error.
I think this is related to the program running in a VM. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#define ARR_LENGTH(x) sizeof(x) / sizeof(x[0])

int main()
{
printf("Hllo world!\n");
int sent = 10;
char hello[] = {'a','b','c','d','e','f','g','h'};
printf(sizeof(hello));
printf(ARR_LENGTH(hello));
return 0;
}


Am I missing something, or is the VM likely the problem?

Answer

You just need to read the printf() documentation carefully. It doesn't take an integer as its first argument.

The problematic lines are:

 printf(sizeof(hello));
 printf(ARR_LENGTH(hello));

It should be:

 printf("%zu\n", sizeof(hello));
 printf("%zu\n", ARR_LENGTH(hello));

(%zu is the format specifier to print size_t values).

My gcc compiler produces the warning:

warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [-Wint-conversion]

for those two statements. Up the compiler warning levels (in case you don't get them alrready).