-4
str = (char *) malloc(15);

If I do not type (char *), is there any difference in my program?

If I try to free the memory with free(str), linux freezes unexpectedly after running program.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Bill N.
  • 15
  • 2
  • Show us what you do with `str`. I don't see any problem with `free` so far. – qwertz Dec 12 '15 at 15:21
  • I can t upload the program. I will use valgrind to track the memory error. Thanks. – Bill N. Dec 12 '15 at 15:27
  • That's why questions are supposed to be Minimal, Complete, and Verifiable http://stackoverflow.com/help/mcve. Valgrind is hunting for mosquitoes with a shotgun. – msw Dec 12 '15 at 17:46

2 Answers2

0

If you program in C, it does not make a difference, the preferred syntax is actually

char *str = malloc(15);

If you were programming in C++, the return value from malloc() would not be cast implicitly as char * for storing into str. But in C++, you should not use malloc() anyway, you should write str = new char[15]; and free this memory with delete []str;.

A potential reason for free(str); to cause undefined behavior is your writing to the array pointed to by str beyond the first 15 bytes.

Use valgrind to help track down where this happens.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

char *malloc(size) unsigned size;

malloc() is used to allocate a certain number, size, of free memory and return a pointer to the beginning of it. The malloc() function is part of the dynamic allocation routines. If an allocation request fails- that is, if there is insufficient memory to fill the request- a null pointer is returned. You always must be very careful to make sure that you receive a valid pointer from malloc().

This is the general form of a program that will allocate 80 bytes of memory and then free them.

 main()
        {
          char *p;
          p= malloc(80);
          if(!p){ printf("out of memory\n"); exit(2); }
        .
        .
        .
        free(p);
        }
Alex
  • 8,461
  • 6
  • 37
  • 49