254
u/wolfjazz93 2d ago
Allocating 1 byte and assigning to int ptr. 🥺😭😭
39
u/ClipboardCopyPaste 2d ago
uint8_t
17
u/yjlom 2d ago
char would be the correct answer, as the C standard doesn't mandate a byte be 8 bits (6 and 32 are very uncommon nowadays but not unheard of, and there's a few machines out there that get really creative).
6
u/mckenzie_keith 2d ago
So even on weird platforms where char is a 32 bit type, sizeof (char) is 1, right? I can't remember.
2
u/AnnoyedVelociraptor 2d ago
FYI char in Rust is 32-bits, maximum size of a UTF-8 character
6
2
u/cowslayer7890 2d ago
And in Java it's 16-bit, which means some Unicode characters get split in two
1
u/Xirdus 1d ago
Rust's char stores UTF-32, not UTF-8, but yes.
1
u/AnnoyedVelociraptor 1d ago
I did some more reading, and I wonder if it is more correct that Rust encodes Unicode Scalars as
char?
40
u/SeriousPlankton2000 2d ago
You asked them to find a bug.
You didn't ask them to find a bug in your code.
18
u/inaem 2d ago
Joke from last year or recent, can't tell with how often Gemini updates their models. /s
19
u/1XRobot 2d ago
This is what it actually returns:
#include <stdlib.h> int main(void) { int *x = malloc(sizeof(int)); // Allocates correct byte size for an int (typically 4 bytes) if (x == NULL) { return 1; // Good practice: Handle allocation failure } *x = 42; // Safe write operation free(x); // Correctly frees allocated block return 0; }
44
u/PR8-E 2d ago
int* x = (int*) malloc(sizeof(int)); Since malloc returns void pointer you should parse it to type you use.
35
u/yjlom 2d ago
void * coerces to any pointer type. This is valid:
int *x = malloc(sizeof(int));. This is also valid (in C23):auto x = (int *) malloc(sizeof(int));.31
u/Mateorabi 2d ago
Get off my lawn with your newfangled auto keyword.
7
u/ibevol 2d ago edited 2d ago
Cringe. It’s fine to use auto when the type is clear on the same line. In c++ the following is idiomatic:
auto ptr = std::make_unique<int>(42);over specifying int twice
std::unique_ptr<int> ptr = std::make_unique<int>(42);However, the following should not be considered idiomatic:
auto ptr = get_ambiguous_pointer();It’s the same principle here.
1
u/yjlom 2d ago
The keyword ain't new, it's been used as a storage specifier since forever. What's new is overloading it for type inference.
5
2
u/mydogatethem 2d ago
Is this different between C and C++? In C++ you absolutely cannot assign a void* to an int* without casting it. You can always do the reverse: a void* can be assigned any type of pointer.
3
u/vetgirig 2d ago
In C++ you do not really use "malloc", In C++ you use "new" instead.
1
u/mydogatethem 2d ago
I mean… yes you do, but not really. There are use cases for both. Not everything is a class and not every API you call is even going to work with that buffer you pass in unless the API can free() it. See posix for example.
Anyways, that wasn’t the question I asked and is not even relevant to the question I asked.
5
3
3
u/Direct-Quiet-5817 2d ago
That thanks is meant to safeguard the coder during the future AI uprising.
11
u/AdBrave2400 2d ago
Didn't return anything from an int function in the original code
24
u/ATE47 2d ago
it’s not mandatory for main
9
u/AdBrave2400 2d ago
I thought that was specific to C++. Thanks I didn't know it's been a thing since C99
5
u/usa_reddit 2d ago
There are multiple bugs:
int *x = malloc(1); Dynamically allocates 1 byte of memory on the heap. This is bad because an int is usually 4 bytes, it should be
int *x = malloc(sizeof(int));
free(x) deallocates the memory on the heap thus *x becomes a dangling pointer, but the code will still run since it is pointing to the programs heap (allocated memory). It is just undefined behavior since you have no guarantee what is being stored at that memory location.
This is why pointers in C can be dangerous.
1
u/morimando 2d ago
“Use after free”, eh?
Isn’t that like one of the more prolific security issues? 😄
1
u/Ok_Reserve_8659 2d ago
I once asked Claude if it could install a node library version 1.1 from remote. I wrote the library and so The local copy was on the machine there but there was an issue connecting to the server . Claude decided to alias version 1.1 to the local copy instead of reporting that there was a connection error 😭
2
0
u/YeetYourSkeet 1d ago
I know this is just a joke, but you can make anything sound stupid when you make up a fake scenario to attach to it. If you actually ask AI, it correctly identifies the issue.
1
1
u/gerbosan 1d ago
😓 and I was thinking the joke was asking Gemini as it is never taken seriously in the list of agents for developers.
Also have to man up, have to learn C.
1
u/SirMarkMorningStar 1d ago
What happened to new and delete? You kids get some wacky new libraries since I switched to Java (and then switched to JavaScript and Python)?
2
u/LostgamerFJ 2d ago
I'm not good enough at programming for this. What do the "free" and "malloc" functions do?
28
u/LucyShortForLucas 2d ago
They are core C functions. malloc allocates N bytes of memory, free frees that memory. * is t he dereference operator, so *x is trying to dereference freed memory, which is undefined behavior
3
u/DiodeInc 2d ago
I thought * was a pointer. Isn't it? How is it dereferencing freed memory?
Or is it because it's returning *x that's the bug?
8
3
u/ThomasScotford 2d ago
* is the dereference operator, but in the context of variable declaration, it specifies the variable is a pointer to a type.
-Thomas Scotford
1
u/ArjixGamer 2d ago
Why are you leaving a name signature in your comment, when your username is the same as that name?
4
u/LostgamerFJ 2d ago
That explains a lot. I mainly code in Java and python, as I'm a beginner and have never touched c
2
u/conundorum 2d ago
That makes sense. Java in particular does a lot of this under the hood; anything that isn't a primitive is actually a reference (special C++-style pointer with non-pointer syntax), and
newis a combination ofmalloc()& objection creation. (deleteshould be a combination of object destruction &free(), but they had to change how it works to accomodate the garbage collector.)C (and C++) just makes you do the actual bookkeeping yourself.
6
u/Independent_Spell_55 2d ago
If I remember correctly, Malloc allocates memory, and I assume free would free up that memory, so when the variable is returned it doesn’t exist. I don’t have much experience with manual memory management so take anything I said with a grain of salt.
1
u/Mateorabi 2d ago
“If I remember correctly”. Please hand in your programmer badge and compiler to the officer at the front desk.
7
u/Scratch137 2d ago
"malloc" is used to allocate a given number of bytes in the heap. for example, int x* = malloc(5) allocates 5 bytes in the heap and sets x to the address of the first byte.
"free" releases heap-allocated memory. in this case, free(x) frees up the 5 bytes we allocated earlier.
2
u/abc9hkpud 2d ago edited 2d ago
Malloc allocates memory. It takes as input the number of bytes, so in this case you need something like
Int* x = (int) malloc(1sizeof(int))
For an int array of length 1. Free is used to free the pointer.
After free, you shouldn't access the memory (or return it for someone else to use)
Modern C++ uses new and delete instead. Malloc and free are used in C
1
1
u/JustACasualReddittor 2d ago
This is C. Malloc is "memory allocation" and it will essentially "reserve" a certain amount of memory to store data (an integer in this case) and return the adress of that allocated memory (known as pointer). So now you can point at that adress and read a value or write a new one.
Free is the reverse, it frees the memory space so now it can be used by something else in the program. In a lot of languages all memory is freed automatically after the program stops executing, but not C. If you don't free the memory other programs can't use it. (It gets freed eventually in modern computers tough)
3
u/yjlom 2d ago
Malloc works on top of OS mapping, which gets freed as soon as the program is terminated.
2
u/vetgirig 2d ago
Yes any memory allocated to a program is automatically returned to the operating system when the program exit and stop running.
However malloced memory who aint got a free in a server program will continue to increase the memory heap until the program is terminated with out of memory since all available memory has been used by the program. But that is just for the program.
Operating systems usually do not have that problem. Well, most operating systems do not have that problem. For example Windows 95 was prone to that error.
1
u/yjlom 2d ago edited 2d ago
Malloc(n) attempts to allocate a region of memory of size n bytes, preceded by a descriptor for free to use. It has its own memory buffer that it tries to use first; if it's out of memory, it asks the OS to allocate more RAM to the process; if that fails (due to running out of RAM or OS policy), it returns 0, aka NULL. If it succeeds at any point, it returns a pointer to just before the data (and just after the descriptor).
Free(p) will look for a malloc-written descriptor just in front of *p, and notify malloc that it's no longer in use and can be recycled.
This code is buggy because:
- It allocates only 1 byte, while int usually takes 4 bytes (C allows for a byte to be any length at least 6 bits, while an int must just be a non-zero natural amount of bytes long). It should instead be malloc(sizeof(int)).
- In the second example, it tries to read the pointer after free, but at that point malloc might already have reused the memory for something else or given it back to the OS.
- It fails to check that malloc actually succeeded, which is ok here because it doesn't do anything with it, but any more complex program would crash or worse if it didn't.
0
u/MetaNovaYT 2d ago
They’re heap allocation and deallocation functions in C/C++. ‘malloc’ requests a specified number of bytes to be allocated by the OS, and it then returns a pointer to that memory which can be used to store any value (or values) you want.
‘free’ tells the OS to deallocate that memory so it can be used for future allocations if needed, so after freeing the memory, the pointer from ‘malloc’ points to memory your program no longer has ownership of.
The bug that Gemini added is trying to read the value at that pointer after the memory has been deallocated, which will most often cause a crash because your program tried to access memory it doesn’t have access to anymore
2
u/Rajarshi1993 2d ago
In my experience, coding agents can typically catch this kind of simple bug accurately.
349
u/AdBrave2400 2d ago
Is the mistake that they're allocating 1 byte and storing in a pointer to an int which is 4 bytes?