1

I wrote the following program:

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

int main(void)
{
        char *s;
        s = (char*)malloc(15);
        s = "Hello World";
        printf("%s",s);
        free(s);
        return 0;
  }

There are no compilation errors. I'm getting this run time error: * Error in `./s': munmap_chunk(): invalid pointer: 0x0000000000400694 * Hello WorldAborted

Why am I getting this run time error and how can I fix it? Is it because after the call to malloc, s received a certain address, and the assignment s = "Hello World" modifies the address of s, but then when doing free(s), the pointer that is sent to free is not the one that was returned by malloc?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Tree
  • 145
  • 1
  • 13

1 Answers1

6

Is it because after the call to malloc, s received a certain address, and the assignment s = "Hello World" modifies the address of s, but then when doing free(s), the pointer that is sent to free is not the one that was returned by malloc?

Yes

    s = (char*)malloc(15);
    s = "Hello World";

You are overwriting the returned address of malloc (memory leak)

free()

if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), or strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Change s = "Hello World"; to strcpy(s, "Hello world");

Also, take a look to Do I cast the result of malloc?

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    Thank you very much! @Keine Lust – Tree Feb 25 '17 at 09:50
  • @Keine Lust Actually, I'm confused....why would not it be strcpy(&s, "Hello world"); ? I mean if we send s, then why a copy of the pointer s will not be made? Say I have int x = 4; and I send it into a function that receives an int. Then if I understand it well, a copy of that integer is going to be made, in a different address containing the same content of x, which is 4. So if I pass s into a function, why a copy of the pointer s won't be made? Where did I go wrong? Thanks! – Tree Feb 25 '17 at 10:32
  • 1
    No, `strcpy` is expecting a pointer to `char` and `s` is already a pointer to `char` (using the address of operator `&s` results in a pointer to pointer). – David Ranieri Feb 25 '17 at 10:38
  • @Keine Lust Thanks for responding quickly :) So in the call strcpy(s,"Hello World"); the address of s is passed to strcpy? – Tree Feb 25 '17 at 10:45
  • @Keine Lust Thanks, just one last thing: I still don't understand ,when we do need to pass a pointer to pointer to something, and when the address of the pointer itself is passed? Because sometimes I see things like **ptr passed into functions, but with strcpy for example, we don't need to do so. – Tree Feb 25 '17 at 11:02
  • 1
    @Keine Lust Thank you, I appreciate it. – Tree Feb 25 '17 at 11:05