9,374 questions
Best practices
0
votes
3
replies
46
views
C memory initialization for a char** after a malloc
I've been researching this for a day and I've found a lot of conflicting information on multiple websites. I'm writing a simple test that will allocate and initialize a char** (array of strings, char*...
1
vote
0
answers
57
views
How does i in 'scanf("%d", ptr + i);' counts to 4? [duplicate]
I mean that i is incremented by 1 right, then how does ptr + i equals ith block of memory since int size is 4?
int i, n;
printf("Enter the number of Integers: ");
scanf("%d&...
0
votes
1
answer
77
views
Returning memory from glibc malloc non-main arenas to the operating system
I simulated a scenario in Java that leads to severe glibc memory fragmentation.
Step one: simulate a multithreaded environment with 600 threads.
Step two: every second, start two new threads that ...
Best practices
1
vote
7
replies
170
views
Memory allocation when using a linked list
So I'm making a linked list for one of my school assignments in C. I found this website that has some helpful code snippets, and I noticed that they use malloc() to allocate more memory every time ...
2
votes
2
answers
152
views
Simple C malloc question that prints garbage on multiple invocations [closed]
I'm refreshing my C skills (been decades) and ran across something I don't quite understand. I'm working on some code that involves a lot of bit shifting, masking, etc. I have one function that ...
2
votes
2
answers
88
views
mallopt(M_PERTURB) does not perturb the memory on free
I am trying to catch memory-related bugs such as use-after-free by mallopt(M_PERTURB, <value>).
According to the doc, the memory will be initialized to value when it has been released by free.
...
-4
votes
0
answers
102
views
SIGSEV signal after method call - How do pointers work after pass-by-reference?
While implementing a Dijkstra-Search on a Graph, I call a seperate method to perform the search, handing it a pointer to my nodes and direct values for start/endpoint and array size. Notably,t he ...
-6
votes
2
answers
274
views
How to try catch finally in c
I want to try catch the free(hello); so that the free(world); can still be executed for freeing all allocated memory in the main program.
int main()
{
const char *hello = "Hello World";
...
4
votes
2
answers
224
views
How to free the value inside struct in c
I don't know how to reset the value field inside the Hello struct. It's a pointer pointed to an outside passed input argument.
typedef struct Hello {
void *value;
} Hello;
Hello* create_hello() {
...
1
vote
0
answers
80
views
dlmalloc mspace_trim in mspace with all object free
We use the mspace feature of Doug Lea's Malloc often referred to as dlmalloc.
We have an mspace with 250 MB of objects and free all the objects.
After calling mspace_trim() the size is 150 MB.
We were ...
0
votes
3
answers
265
views
What to use when malloc array length in c
When the array type is a "void *", then it can be allocated by:
void **void_array;
void_array = malloc(sizeof(void*) * 1);
But, if the array type is a struct Hello *, then what should be ...
9
votes
4
answers
1k
views
Single-line initialization of array allocated by malloc()
I used malloc to define an index because each line had a different number of elements (simplified example below):
int** Index=malloc(2*sizeof(int*));
Index[0]=malloc(2*sizeof(int));
Index[1]=malloc(3*...
4
votes
5
answers
259
views
What is the alternative to declare a Variable-Length array in C, that may exceed Stack size, without the need of Dynamic Memory allocation?
I have the following code snippet in C that declares multiple one-dimensional and two-dimensional arrays of type double.
double func(double alphas[], double betas[], double rhos[], double **X, ...
3
votes
2
answers
128
views
How to do *user defined reduction* on *allocatable array* and *user reduction functions* with openMP in C?
I have written some programs with OMP reduction directive in Fortran and in C. But the data types were simple (int, float, arrays with fixed size, ...) and reduction-identifiers used were implicitly ...
-2
votes
2
answers
136
views
Facing issues with Structs and malloc in an assignment question [closed]
This was a question in a C Programming assignment given to me as a part of last week's assessment. Requesting everyone to kindly explain what needs to be done and how it needs to be done. Kindly note ...
2
votes
1
answer
112
views
Why does my custom global allocator crash on large allocations, and how can I handle alignment properly?
I am trying to implement a custom global allocator for use in my Rust application. The goal is to track memory usage and align to 64 bytes. My allocator uses libc::malloc and libc::free for allocation ...
6
votes
2
answers
263
views
How do I calculate the end address of a C struct in memory?
I have the following structure in my .c file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student {
char* name;
int age;
int id;
} Student;
...
2
votes
3
answers
206
views
Writing a Von Neumann Ordinal generator in C : Problem with malloc
I want to write a computer programme that will do the following things :
1a. It will make an array 3 characters long.
£££
2a. It will then initialize the array with the string "{_}" and ...
3
votes
2
answers
166
views
Is it safe to call free on std::string_view::data?
Is it safe to call free in the example below:
size_t len = 10;
char* buffer = static_cast<char*>(malloc(len));
std::string_view sview(buffer, len);
free(sview.data())
Why do I need this?
I have ...
0
votes
1
answer
46
views
How does a microcontroller keep track of heap free()?
In a microcontroller without any OS, how does the microcontroller keep track of where a malloc will point to in the heap?
char *x;
char *y;
char *z;
x=(char*)malloc(10);
y=(char*)malloc(10);
free(x);
...
0
votes
1
answer
138
views
Make malloc allocate from already allocated buffer
Is it possible to change malloc or new behavior for a somewhat limited scope to actually allocate out of a given buffer that is already allocated? Eg. something like:
char buffer[1024];
void main(...
2
votes
1
answer
173
views
Does allocating a buffer smaller than the size of a struct cause undefined behavior, even if I do not reference any would-be out-of-bounds members?
Suppose I have the following:
struct S {
char b[256];
};
struct S *buf = malloc(128);
buf->b[0] = 1;
You may notice that the allocation size is smaller than the structure size, but at no ...
0
votes
0
answers
72
views
For memory crunch, should malloc return 0 or OS issue SIGKILL? [duplicate]
I am trying to write a C program that should fail due to memory crunch. It just keeps on malloc-ing without free-ing. After each malloc I check if the returned value is zero. If so, I stop with a &...
31
votes
2
answers
5k
views
Why do modern compilers assume malloc never fails?
In case of failure, malloc returns a null pointer.
In the following code the latest GCC and clang assume malloc never fails and simple remove the branch
#include <cstdlib>
int main() {
if (!...
3
votes
2
answers
127
views
Custom free function doesn't release memory completely, Valgrind reports 'still reachable'
I've been following an article that walks through implementing primitive versions of malloc and free. After finishing the allocator, I wanted to test it using Valgrind, so I added the following lines ...
1
vote
1
answer
183
views
How does C prevent heap growing indefinitely?
I’m investigating how C’s runtime memory allocator behaves in a long-running process that repeatedly:
allocates many blocks of variable size with malloc(),
finishes its work, and
calls free() on all ...
0
votes
0
answers
85
views
_aligned_malloc and implicit object creation
I'm creating a C++ allocator that should over-align the allocated memory by a runtime-determined alignment value.
According to https://en.cppreference.com/w/cpp/memory/c/aligned_alloc, the std::...
3
votes
1
answer
203
views
Why does malloc(10) allocate 24 bytes?
I am experimenting with malloc in C to better understand how memory alignment and allocation actually work behind the scenes. Here is the simple code I am running:
#include <stdio.h>
#include &...
1
vote
0
answers
145
views
kzalloc(32, GFP_KERNEL) failed, but kzalloc(64, GFP_KERNEL) success,
I'm new to Linux kernel development and need help understanding a memory allocation issue. I defined a structure in my driver like this:
typedef struct MyStruct {
int a;
int b;
int c;
...
12
votes
3
answers
698
views
std::malloc() and starting lifetime of the object
Excerpt from the book "C++ memory management" by Patrice Roy
The std::memcpy() function
For historical (and C compatibility) reasons, std::memcpy() is special
as it can start the lifetime ...
1
vote
1
answer
91
views
uninitialized memory when using realloc for an array of structs [closed]
I have a parent struct that has an array of child structs and the length of it, and within each child struct is an array of numbers and the length of it. all of the arrays are defined using pointers ...
3
votes
2
answers
124
views
storing all c stuct arrays in only one single memory segment obtained with malloc/calloc
Suppose I have a database in memory that I want to modify.
Let's say the tables are phone information and items.
The phone information consists of a name up to 99 characters and a character code.
The ...
1
vote
2
answers
121
views
Leak errors in fifo application in c
I'm not sure why my valgrind is spitting heap errors and I've been tracing my code left and right. I have some code, but I'm not sure if more code is needed.
My jobs.h
#include "piper.h"
#...
0
votes
2
answers
161
views
Is this truly best way to delete last element in C? [closed]
I have a code where I need to delete last element of array. I made this code but I am wondering is there a more optimised way of doing this?
My version:
void DeleteLast(int** array, int* size)
{
...
3
votes
1
answer
193
views
Issue with Skipped malloc Breakpoints in GDB When Using finish and continue
Requirement
Track the total memory allocated (malloc) and freed (free).
Capture backtraces of all malloc and free calls (for now, logging can be ignored).
Current Approach
For malloc:
I need every ...
0
votes
0
answers
137
views
Specify Include directory path with llvm build
Trying to set the include directory path for llvm build
Hi,
I am trying to build llvm with snmalloc allocator and as per the cmake options and instructions, I have set LLVM_INTEGRATED_CRT_ALLOC flag ...
0
votes
0
answers
43
views
C, how to fill in an allocated struct with strings of fixed sizes [duplicate]
I am very new to allocating. Below is a simplefied version of my code.
I need to allocate a struct in which variable data needs to be stored that has a set length when it passes through several ...
1
vote
0
answers
74
views
Handling multiple memory mangers in C++
My C++ application is using own library for memory management. It defines malloc and free and it is statically linked. My application uses few other 3rd party libraries also. I got a crash in one of ...
4
votes
1
answer
125
views
Is it safe to use _malloca with std::unique_ptr with a custom deleter to _freea?
_malloca from the Windows SDK does a stack allocation when the requested size is small and a heap allocation when it exceeds a certain size, because of that, _malloca requires a call to _freea. I'd ...
1
vote
2
answers
173
views
Fixed-address mmap call segfault when invoked from main but works inside custom malloc override in C++
I have 3 files. 1.cpp has a function map that uses mmap to do some fixed memory mapping. 2.cpp is a malloc interceptor and 3.cpp has the main function.
The problem is ... depending on from where map ...
-2
votes
4
answers
201
views
Is there a way to increase the size of a memory allocation after initialization C++? [duplicate]
I am trying to increase the amount of memory I have allocated using malloc. Is there a way to increase the size from 128 bytes to 256 bytes by allocating an additional 128 bytes next to the original ...
3
votes
1
answer
119
views
Why cant I free the char buffer after assigning the last index to null terminator (\0) [duplicate]
I'm just confused as to why this keeps giving me an error.
If I just fread the file in and don't assign the last index to the null terminator, I can free the memory after using it. However, if I do ...
2
votes
1
answer
101
views
realloc function dynamic array size more than stated
I am trying to add memory of my dynamic array using realloc. But in my code, realloc is added extra memory to the array.
Suppose initially I want to create array of 5 items than I want to add 3 more ...
1
vote
2
answers
51
views
Cannot use mincore to check whether page allocated by malloc is in ram
Question: Why do mincore failed with "Invalid argument" in the following code?
int main(int argc, char **argv) {
char *ptr;
unsigned int num_of_byte_allocated = 4;
size_t ...
5
votes
6
answers
531
views
Decent ways to handle malloc failure?
Suppose that I need to malloc three times and I would like to make an early return if one of the malloc calls have failed.
My first try:
void test(void) {
int *a, *b, *c;
a = malloc(sizeof(*...
0
votes
1
answer
112
views
Segment fault ( core dumped ) from malloc() but I can't see where the problem is coming from [closed]
I'm new to C, coming from another language and I'm getting this error that I understand now but couldn't find how to fix it inside of my code.
It's pretty simple but even when debugging with printf or ...
0
votes
1
answer
60
views
void* function doesn't retain a pointer to the allocated memory inside another function [duplicate]
I wanted to create a dynamic stack just for learning purposes, but I ran into a problem: I'd like to push() function be able to handle if the dstack isn't initialized, and it works when I go through ...
0
votes
3
answers
222
views
Using malloc to create triple pointer from 3d array to be passed to function which takes a triple pointer as an argument and updates its elements
I am currently attempting to create a triple pointer to point to and update the contents of a statically allocated 3d array in C. The updating of the elements of the array will be completed by a ...
0
votes
4
answers
185
views
Why does malloc initialize the allocated memory to zero? [duplicate]
As far as I know, malloc does not initialize the allocated memory. However, on macOS arm64, all values appear as zero. Why does this phenomenon occur? Is this related to ASLR?
#include <stdio.h>
...
0
votes
1
answer
142
views
realloc fails when running ./out.exe via Makefile, but works when run manually
I'm having an issue where, when I run my already compiled program ./main.exe (gcc main.c -o main.exe) through a Makefile, a realloc call fails when the size goes over 40 bytes. However, if I run ./...