Re: malloc modifying a passed string



Scott Taylor wrote:
I've searched through the FAQ but I can't find this problem, which seems like it should be a newbie one. Here is a following code sample, without the necessary testing of malloc, including of standard libraries, etc...

main() {
  char *ptr;
  ptr = malloc(4);
  strcpy(ptr, "abc");
  some_func(ptr);
  ...
}

void some_func(char *ptr) {
  char *ptr2;
  ptr2 = malloc(5);
  ...
}

Could you provide a minimal example that compiles correctly and exhibits the behavior that you describe?

$ cat foo.c
#include <stdlib.h>
extern int printf(const char *format, ...);
extern char *strcpy(char *dest, const char *src);

void some_func(char *ptr) {
  char *ptr2;
  ptr2 = malloc(5);
  free(ptr2);
}

int main(void) {
  char *ptr;
  ptr = malloc(4);
  strcpy(ptr, "abc");
  printf("%s\n", ptr);
  some_func(ptr);
  printf("%s\n", ptr);
  free(ptr);
  return 0;
}

$ gcc-3.4.4 -std=c89 -pedantic -Wall -Wextra -O1 foo.c
foo.c:5: warning: unused parameter 'ptr'

$ ./a.out
abc
abc

--
Regards, Grumble
.



Relevant Pages