I'm reading this book: "C von A bis Z".
There is this example.
/* ptr14.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Fehler: Funktion gibt die Adresse
* einer lokalen Variablen zurück. */
/* [ Error: Function returns the address of a
a local variable. ] */
// ...
/* Möglichkeit2: Speicher vom Heap verwenden */
/* [ Option2: Use memory from the heap ] */
char *test3(void){
char *buffer = (char *) malloc(10);
strcpy(buffer, "testwert");
return buffer;
}
/* Möglichkeit3: Einen Zeiger als Argument übergeben */
/* [ Option3: Pass a pointer as argument ] */
char *test4(char *ptr){
char buffer[10];
ptr = buffer;
strcpy(buffer, "testwert");
return ptr;
}
int main(void) {
char *ptr;
/* ... */
ptr = test3();
printf("test3: %s\n", ptr);
test4(ptr);
printf("test4: %s\n", ptr);
return EXIT_SUCCESS;
}
I'm understanding the problem the author is talking about.
Why the test4
solution is working?
If I am understanding correctly, doesn't it
- allocate
char buffer[10];
on the stack - assign the address of the first element of
buffer
to myptr
(living in previous scope)ptr = buffer;
my expectation:
Point with ptr
on buffer
should be false, because this scope should be broken/cleaned up.
What is wrong with my thinking?
EDIT 1
I changed test4(ptr);
to ptr = test4(ptr)
and it still works...
Still don't know why test4(char* ptr)
is working...
char buffer[10];
the memory stops existing after}
. You return a pointer to nonexistent memory. I can only guess that in possibility 3 it is expected thatptr
is a pointer to a valid memory before you calltest4
. – Sheolptr = buffer;
fixes the problem somehow, you need a new book. – Khabarovsk