简体   繁体   中英

Memory allocation with malloc?

Below is the snippet of the code:

int main(void) {

    char sizing[] = "manshcanshcnams cndhan sndhcna snshans";
    char *xyz = malloc(sizeof(char));
    printf("%ld\n",sizeof(xyz));
    xyz = sizing;    // IT SHOULD FAIL HERE
    printf("Fail %s\n",xyz );
    return 0;

}

As you can see that I am trying to assign more memory to xyz then what it can hold. But the output doesn't fail. Is it an undefined behaviour?

You can't copy strings with = . xyz = sizing just modifies the variable xyz so that it points to the array sizing , instead of pointing to the memory you malloced.

So, your memory is leaked but there is no undefined behavior (except that you forgot to include <stdio.h> and <stdlib.h> ).

All you're doing is telling the pointer xyz to point at the memory address associated with sizing . There is no reason that this would fail.

My understanding is that malloc() should not fail unless it cannot allocate the amount of memory it was asked for. However, when you use it, you are required to release that memory when you don't need it anymore or else your program will request more and more memory and eventually the request will fail because you haven't released anything.

Also, not all illegal memory operations cause an error, for example ( code edited 2013-03-08 based on Kludas's observation that the previous version wouldn't compile ):

#include <stdio.h>
#include <string.h>

int main(void)
{
    char myString[4];
    strcpy(myString, "abcdefghijklmnopqrstuvwxyz");  /* This overflows the buffer */
                                                     /* but MIGHT NOT cause an    */
                                                     /* immediate crash!          */
    printf("myString = [%s]\n", myString);
    return 0;
}

This may-or-may-not trigger an error, but it is certainly illegal because I am writing 26 characters into an array that should only hold 4 items (three characters plus a terminating NULL).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM