ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
1. problem. I get a seg. fault at first comment in func2 - how come? I´m not doing anything different with dst, than I'm doing with src.
2. problem. I need to make src point at the memory pool dst is pointing at - func2 at 2. comment. Can someone please explain what I'm doing wrong here?
You need to pass a pointer to the pointer if you want to update that pointer with the newly allocated memory. You already know that you can't do this:
void func(int a)
a = 4;
int num = 5;
That program will still print 5 because func() has its own local copy of the number and that's the only one that it's modifying. When you pass src to your function, it's modifying its own local copy so the calling function's src is still pointing to the free()'d memory. BAM! Seg. fault. Instead, you have to do something like this:
hmm well I'm asking because I'm using compress2() from zlib.h and it takes 2 ByteF pointers
int compress2(ByteF *dest, uLong destLen, const Bytef *source, uLong sourceLen, int level)
This function (as you probably know) compresses source and saves in dest. If a function always make a local copy, when ever a pointer is passed (and the prototype of the function is char *), how can compress2 save in dest?
say func4(char *dst, char *src)
You shouldn't be able to e.g. strcpy somethink over in dst, and access it in parent scope right? But this is what compress2() does!
When you pass a char * to a function, you're not passing the allocated memory that the char * points to, you're passing the address of the memory. The reason your original example was failing is because you're modifying the pointer in the called function. strcpy() is a good example of how this works. You pass it a pointer to allocated memory in which it can store the second string.
You can see, mystrcpy() actually modifies dst by incrementing it a bunch of times, but when you return to main(), buf still points to its original location. But in your original code, you were free()'ing the memory that dst pointed to and then allocating new memory for it. So when it got back to the calling function, dst still pointed to the free()'d memory instead of the newly allocated memory.