If i have a pointer with some information already in it and then make a malloc() call, does this assign additional memory space to the pointer variable or does it overwrite the memory space which I already have assigned?
If i have a pointer with some information already in it and then make a malloc() call, does this assign additional memory space to the pointer variable or does it overwrite the memory space which I already have assigned?
It overwrites the pointer.
The memory it used to point to still exists, but you might not be able to get to it any more (this is a memory leak).
Use realloc if you want to expand what you've already got.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
How can it increase the space? Is it psychic somehow?
I think you fail to understand how basic C works.
malloc is not psychic; it does not know whether you've allocated anything before the current call or not and just returns a memory block of the specified size. It returns an address and addresses are stored in pointers, so you're just overwriting the previous address stored in the pointer you assign it to.
I'm attempting to use the realloc() function but I keep getting:
*** glibc detected *** ./simple: realloc(): invalid next size: 0x0962c740 ***
and then a backtrace and I'm not too sure why. Here is the code for realloc() which I have:
I know that it is something in my syntax of the second argument of the realloc() because if I just substitute BUFSIZ there it runs fine. I was just trying to allocate enough memory for the amount of data that is read in.Code:nt myHTTPclientResponse(int socket, char *code, char *message, char *server, char *lastModified, char *date, char *contentType, int contentlength, char *body) { char mess_in[BUFSIZ]; int nr; int ret; if((nr=read(socket, mess_in, BUFSIZ)) < 0) { fprintf(stderr, "Trouble Reading From Server.\n"); fprintf(stderr, "Errno Value: %s\n", strerror(errno)); } strncat(message, mess_in, BUFSIZ); while (nr != 0) { if(ret = (realloc(message, nr *sizeof(char))) == NULL) { fprintf(stderr, "Trouble with relloc function trying to assign more memory to *message\n"); fprintf(stderr, "Errno Value: %s\n", strerror(errno)); } strncat(message, mess_in, strlen(mess_in)); memset(mess_in, '\0', BUFSIZ); if((nr=read(socket, mess_in, BUFSIZ)) < 0) { fprintf(stderr, "Trouble Reading From Server.\n"); fprintf(stderr, "Errno Value: %s\n", strerror(errno)); } } // fprintf(stdout, "%s\n\n", message); return nr; }
Last edited by NuNn; 02-12-2009 at 12:24 PM.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
I will initialize it do 0 just to be safe anyway to make it more better practice