0

I tried compiling this example on both Mac (10.10.5) and Linux (RedHat 5.5):

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

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %s\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %s\n", str, str);

   free(str);

   return(0);
}

I receive no errors when compiling and running the executable on Linux (gcc) and receive the following output:

String = tutorialspoint,  Address = 294019088
String = tutorialspoint.com,  Address = 294019088

But I receive these errors when compiling on Mac (gcc):

testmemalloc.c:12:48: warning: format specifies type 'unsigned int' but the argument has type 'char *' [-Wformat]
   printf("String = %s,  Address = %u\n", str, str);
                                   ~~          ^~~
                                   %s
testmemalloc.c:17:48: warning: format specifies type 'unsigned int' but the argument has type 'char *' [-Wformat]
   printf("String = %s,  Address = %u\n", str, str);
                                   ~~          ^~~
                                   %s
2 warnings generated.

but the executable outputs a number as expected:

String = tutorialspoint,  Address = 1631603760
String = tutorialspoint.com,  Address = 1631603760

Now, please forgive the stupid question, I'm new to C (and not a programmer). Even though the executable runs and outputs a number as expected, can someone please explain the difference here due to OS and the potential impact, if any?

goodbenito
  • 29
  • 2
  • 2
    In your code, the print statement has this: `Address = %s` but in the compiler warning it's `Address = %u`. Can you show us the actual code you are compiling with? Regardless, you should be doing it like this: `printf("%p\n", (void*)str);` – Random Davis May 20 '16 at 16:32
  • 2
    `printf("String = %s, Address = %u\n", str, str);` --> `printf("String = %s, Address = %p\n", str, (void*)str);` – BLUEPIXY May 20 '16 at 16:33
  • You do not need the cast in front of the `malloc`. In fact it is a bad idea – Ed Heal May 20 '16 at 16:34
  • 2
    @EdHeal, please do not start this! :) – SergeyA May 20 '16 at 16:37
  • "new to C" + "warning: ..." means you are 99.99% certainly doing something you should not, but C allows as C _trusts_ you know what you are doing. Welcome to coding without a safely net. Treat warnings as _errors_ and insure all warnings are enabled. – chux - Reinstate Monica May 20 '16 at 17:00

0 Answers0