0

Insufficient buffer, but flawless allocation!? How's it possible?

Hello friends. Today I encountered a strange thing in C. Please look at the code below : char* x; char y[] = "123"; strcpy(x, y); fputs(x, stdout); Running this code will lead to a segment fault. The reason is clear and it is because we've not provided variable 'x' with an appropriate amount of buffer. This will be fixed using malloc() function: x = malloc(sizeof(y)); And it is because 'x' has sufficient buffer to store those characters. Now if I do this: x = malloc(0); it will still work, without any error. WHY ?? I passed no room to 'x' to have, in order to store any character! But it still works as expected! But I guess it should've given a segment fault just like previous time, can you clear this up to me ?? Can you let me know what's going on here ?

1st May 2023, 5:01 AM
Ali_combination
Ali_combination - avatar
15 Respostas
+ 4
because strcpy does not actually check whether the destination buffer has sufficient space for the data to be copied. Therefore, when you call strcpy(x, y); with x = malloc(0); the strcpy function simply tries to copy the contents of the source string y to the destination buffer pointed to by x, without checking whether there is enough space to store the contents. However, attempting to access memory beyond the allocated block size is undefined behavior in C, which means that the behavior of your program is not guaranteed and may vary depending on the system and compiler used.
1st May 2023, 5:30 AM
Just Some Random Guy
Just Some Random Guy - avatar
+ 3
In short, because C often lets you do unsafe things with memory and pointers. If you cout x, (x+1), and (x+2) you'll see that all three values got copied, in order, just like you told it to, even though x doesn't actually "own" the latter two memory addresses. Problem is, if anything else was using those addresses, you've just overwritten their data. PS speaking of unsafe memory operations, since you're using malloc don't forget to free the memory when you're done, or it'll just hold onto it until the program ends (colloquially known as a memory leak), because C also doesn't have garbage collection.
1st May 2023, 5:54 AM
Orin Cook
Orin Cook - avatar
+ 3
Smith Welder beware that your example does not show the size of storage that malloc(0) allocated from the heap. Instead, sizeof ptr shows the size of the (char *) pointer variable, ptr. You would get the same output of 8 after ptr = malloc(10), ptr = malloc(100), or ptr = malloc(1024).... If you wish to determine the actual size allocated, you have to use an API call to request the OS to read the allocation table. There is no portable way to do this. There is some discussion about it here, with handy macro definitions for a few popular OSs: https://stackoverflow.com/questions/1281686/determine-size-of-dynamically-allocated-memory-in-c
1st May 2023, 2:48 PM
Brian
Brian - avatar
+ 2
/*malloc grab multi-page chunks, 8 or 16 byte chunks*/ char *ptr = malloc(0); printf("%ld",sizeof(ptr));//got 8 byte } /* It depends on cpu, OS, and malloc implementation of course,.. in the end, if it's undefined behavior, no promises are being made by the language.. Clang doesnt say what'll happen, program may crash, or could wipe your hard drive...etc */
1st May 2023, 12:15 PM
Smith Welder
Smith Welder - avatar
+ 2
Bob_Li yes, new progmrs at C, think that some things forbidden by C, and that won't work, but that's a big mistake..
1st May 2023, 1:39 PM
Smith Welder
Smith Welder - avatar
+ 2
Brain, yes, I just showed that isn't zero, at least 8 byte for ptr, and you can look at some discussion too https://prog21.dadgum.com/179.html Also you can look at docs: If size is zero, the behavior of malloc is implementation-defined.. https://en.cppreference.com/w/c/memory/malloc As I said before, it depends on cpu, OS, and malloc implementation, it's can get 8,16,32,64..etc probably it's can get all free space on some ioT.. get ub.. etc
1st May 2023, 3:26 PM
Smith Welder
Smith Welder - avatar
+ 1
Snehil in some cases, I may have to use safe version of strcpy() instead of this one ... but one question. 'x' must have some space to show that content after all, right ? because when it shows the content it means it HAS the content. And HAVING some content requires its sufficient space. How is it done ? How is this unsafe operation handled ? Is the compiler (or the strcpy() itself) forced to provide 'x' with some space ?
1st May 2023, 6:45 AM
Ali_combination
Ali_combination - avatar
+ 1
Ani Jona 🕊 'x' uses a valid memory segment (that is also writeable), but it doesn't belong to the 'x' itself? Is this what you mean ?
1st May 2023, 7:06 AM
Ali_combination
Ali_combination - avatar
+ 1
Ali_combination you should concentrate on what malloc(0) is. It is implementation dependent. No guarantee. Best not to use.
1st May 2023, 7:59 AM
Bob_Li
Bob_Li - avatar
+ 1
https://code.sololearn.com/cGWCXFRzDW1B/?ref=app check this code it explains what actually is happening About how to safely handle it: use strncpy instead Bob_Li I would say let's explore every possibility who knows when it comes to play.
1st May 2023, 8:09 AM
Just Some Random Guy
Just Some Random Guy - avatar
+ 1
Snehil Explore is good, but I would still avoid it. I mean, the concept of malloc(0) in itself is sus. what does it mean? how do you free it? what can it do? I feel that malloc(0) is one where the advise: "just because you can, doesn't mean you should" would be good to follow.
1st May 2023, 8:14 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li please just consider that, malloc(0) is not the point. I actually meant, how is such an operation handled when I allocate lesser amount than required ? For example, I need to allocate 100 bytes, but instead I allocate 64 bytes: x = malloc(64); while this still works..
1st May 2023, 8:24 AM
Ali_combination
Ali_combination - avatar
+ 1
Bob_Li hmm ok, I didn't know that the term flawless may make people misunderstand my question. By this word, I meant the process of allocation seems to be carried out without any problem. No error, no warning.
1st May 2023, 11:49 AM
Ali_combination
Ali_combination - avatar
+ 1
Smith Welder agreed. Ali_combination no error is not a guarantee when you're in undefined behavior territory. Think of it as wandering on uncharted territory...you have to ask yourself if it's worth the risk of possibly leaking memory or crashing the program for the gain (if any) you get from doing it this way.
1st May 2023, 12:42 PM
Bob_Li
Bob_Li - avatar
0
Ali_combination you're right. strcpy() 's irresponsible behavior is the one to blame.😅 So the title should be careless allocation, not flawless allocation.
1st May 2023, 9:26 AM
Bob_Li
Bob_Li - avatar