FAQ Database Discussion Community


malloc and free in linux aborted [closed]

c,linux,malloc,free
I have a big C program (64bit), it uses a lots of malloc function call. When I run it in Visual Studio or in Windows platform it works fine. But when I try to run it in Linux I have a problem with malloc() and free(). It is aborted while...

Difficulties with understanding reallocating using malloc

c,memory-leaks,malloc,runtime-error
I am trying to increase the size of my collection structure using malloc instead of realloc. I'm afraid I've made mistakes while assigning variables because I'm getting: malloc: *** error for object 0x7fd46b404ac8: pointer being freed was not allocated I would really appreciate if you could give me a helpful...

Can we use the notation of an array for a memory allocated by malloc?

c,arrays,malloc
I found this piece of code, and I don't understand what it means. Do we have the right to use the array notation like here? double *myList = malloc(3 * sizeof(double)); myList[0] = 1.2; myList[1] = 2.3; myList[2] = 3.4; EDIT : I think this notation uses the fact that...

Changing the pointer inside a function does not reflect outside the function [duplicate]

c,pointers,malloc,pass-by-reference,pass-by-value
This question already has an answer here: How can I allocate memory and return it (via a pointer-parameter) to the calling function? 11 answers void alloco(int *ppa) { int i; printf("inside alloco %d\n",ppa); ppa = (int *)malloc(20); ppa[15] = 9; printf("size of a %d \n", sizeof(ppa)); for(i=0;i<20;i++) printf("a[%d] =...

How will you free the memory allocated?

c,memory-management,malloc,free,dynamic-memory-allocation
I need to free some memory allocated on my program. Can I use something to clean the memory when I need it ? #include<stdio.h> #include<stdlib.h> #define MAXROW 3 #define MAXCOL 4 int main() { int **p, i, j; p = (int **) malloc(MAXROW * sizeof(int*)); return 0; } ...

function to get 2d-arrays from stack and heap

c,arrays,memory,memory-management,malloc
Consider a simple struct, Foo, which contains a pointer to some other strucrt, Baz. and a two-dimensional array, (stack-allocated): Foo arr[ARR_SIZE][ARR_SIZE]; Next, consider a function which mallocs (in the heap, obviously) a memory for a new 2d-array of Foos. A code snippet: Foo** arr_copy = malloc(sizeof(Foo*) * ARR_SIZE); for (int...

How I can add an adjacency list to a node of defined type in C?

c,struct,malloc
I have a defined node type for graph node: struct node{ int data; int neighboursNumber; node * neighbours; }; And I am trying to add for each node some neighbours like this: node * n1 = (node *)malloc(sizeof(node)); n1->data = 1; n1->neighboursNumber = 2; n1->neighbours = (node *)malloc(sizeof(node) * n1->neighboursNumber);...

How to use munmap custom malloc

c++,c,malloc,mmap
I'm trying to recode malloc and free functions but i got a problem with munmap.. With my custom malloc, I create a pool of memory with mmap (Ex : 4Kb), so I can return an index of this pool as an address when my malloc is called. This work fine,...

Failed to add a node to linked list

c,pointers,segmentation-fault,malloc,dynamic-memory-allocation
i make the changes but i cant add more than 2 nodes its will freez but if 1 or 2 node will work well what is the reason??? i gave_up i can do nothing for that This is my code till time #include <stdio.h> #include <stdlib.h> #include <ctype.h> struct info{...

__free_hook doesn't hook as expected

c,malloc
From this stackoverflow question's selected answer. I decided to log the calls to free too. I made a logging free. But the calls to free doesn't seem to be outputted correctly. #include <malloc.h> static void *(*old_malloc_hook)(size_t, const void *); static void *new_malloc_hook(size_t size, const void *caller) { void *mem; __malloc_hook...

Word translator program based on string comparison - heap memory assertion fails

c,arrays,string,malloc,dynamic-memory-allocation
I made a program that reads from file english_dictionary.txt the 200 most frequently used words in the English language, and in foreign_dictionary.txt I put the translations of the respective words in a foreign language. The content of the .txt files is placed in two char * type array of 200...

At what size should I malloc structs?

c,memory-management,struct,malloc
Most examples using structs in C use malloc to assign the required size block of memory to a pointer to that struct. However, variables with basic types (int, char etc.) are allocated to the stack and it is assumed that enough memory will be available. I understand the idea behind...

Cannot free fileName char * after fclose

c,memory-management,malloc,free,realloc
I am trying to free my file name (char * pointer) but got an error : Heap corruption detected: after normal block (#65) at 0x.... The code: static FILE *initializeIndexFile(char *database, char **indexFileName) { FILE *file1_p; *indexFileName = NULL; int len = strlen(database); *indexFileName = (char *)malloc(len *sizeof(char) + 1);...

Freeing a copy of a pointer to malloc'd memory in C

c,pointers,copy,malloc,free
Couldn't seem to find an answer to my question elsewhere. Consider the code: int *ptr = malloc (sizeof (*ptr)); int *dummyPtr = ptr; free (dummyPtr); printf ("ptr: %p, dummy: %p\n", ptr, dummyPtr); As I understand it, free() takes in a pointer and makes it point to NULL aka (nil). I.e.,...

Include source code of malloc.c in gdb?

c,debugging,gdb,malloc
How can I include/view the source code of malloc in gdb? I want to do a step by step execution in gdb, and step into malloc.c source code when any of the malloc functions is called. Currently what gdb says is: malloc.c: No such file or directory. This guy here...

Passing pointers to functions with and without &

c,pointers,malloc
I am trying to understand when I need to use the address-of operator & when passing arguments by reference (for readers that mind my imprecision please read this as simulate pass-by-reference) to functions without modifying the function itself. I will give two small examples using structs. In both the struct...

Working with malloc, char array and pointer

c++,arrays,pointers,char,malloc
I'm trying to understand how malloc and characters arrays(c style) work. Consider the following code, // Example program #include <iostream> #include <cstdlib> #include <iomanip> using namespace std; int main() { //section1: Init char line0[10] = {'a','b','c','d','e','f','g','h','i','j'}; char line1[10] = {'z','y','x','w','v','u','t','s','r','q'}; //section2: Allocate Character array char* charBuffer = (char*) malloc(sizeof(char)*10); cout<<sizeof(charBuffer)<<endl;...

Why the value of root is printed as 0 in main function?

c,pointers,malloc,free
#include <stdio.h> #include <stdlib.h> struct nodeTree { int data; struct nodeTree* left; struct nodeTree* right; }; struct nodeTree* insertRoot(struct nodeTree** root, int data) { if(!(*root)) { struct nodeTree *temp = malloc(sizeof(struct nodeTree)); if(!temp) { exit(-1); } temp->data = data; temp->left = 0; temp->right = 0; (*root) = temp; free(temp); return...

Allocate struct vector memory dynamically

c,vector,struct,malloc
I don't know what is the correct way to allocate memory dynamically: I have a .csv file wich have like 50 lines and I need to allocated enough space in memory to save each line of the file in one space of the struct vector. Also, I know that the...

is this code correct?If yes then malloc is already assigning the addresses to name[i] variable then why strcpy is used?

c,string,pointers,malloc,strcpy
Following is the piece of code char str[20]; char *name[5]; for(i=0;i<5;i++){ printf("Enter a string"); gets(str); name[i]=(char *)malloc(strlen(str)); strcpy(name[i],str); } When in line 5 address of each string(denoted by str variable) is stored in name[i] array, then why this code is copying each address into name[i] using strcpy()?...

Malloc an array inside a struct

c,arrays,struct,malloc
I'm trying to malloc an array inside a struct but I keep getting segmentation errors when I run the program. The compares function is just something I'm testing so it shouldn't be a part of the problem typedef struct { char *string; } prod_t; int main(int agrc, char **argv){ int...

Random double free or invalid next_size

c,malloc,size,free
So I'm having a problem right now with my program (well, more with the shared library I've written). I'm trying to implement a TCP/IP stack, and am currently trying to implement ARP. ARP works, both resolution and replies, however my ARP Server will randomly crash (sometimes running for 10-20min, being...

copying the content of an dynamic array of structs into another dynamic array using memcpy

c,struct,malloc,memcpy
I want to copy the content of a dynamic array containing 2 structs to another dynamic array of the same size. I need an exact copy. When I compile, I get these 2 errors at the last line: invalid use of undefined type ‘struct student’ & dereferencing pointer to incomplete...

Infinite loop with fread

c,arrays,loops,malloc,fread
I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

c free() works when I call but not in my function

c,memory,malloc,free
I am learning C and I am playing with malloc and free. But for some reason when I use free() in the main everything works but when I put it in my function it does not #include <stdlib.h> #include <stdio.h> struct st { int number; }; void del(struct st *s)...

How use index in a pointer with Struct and pointer in C

c,pointers,struct,malloc,realloc
I need to make a program that can register some car. Then I need show all the cars registeres. I can't make this work, when I execute the code below the printf show just memory trash, and just the last car appears right! Code (I have a menu function that...

Malloc , Realloc , Memset : Struct pointers , arrays of char, int

c,pointers,char,malloc,realloc
#ifndef vECTOR_h #define vECTOR_h #include<string.h> #include<stdio.h> #include<stdlib.h> /* My iterator is an int but thanks to this typedef I could change it easily */ typedef int iterator; #define iterator_begin 0 #define iterator_end -1 //typedef is for vector_type and in the meanwhile struct vector_struct is defined typedef struct vector_struct { size_t...

Anomalous behavious of fgets()

c,malloc,fgets
Input Format The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow. Each line contains a binary string of length M. If the ith line's jth character is 1,...

Not sure how to use malloc() and free() properly

c,pointers,memory-management,malloc,free
int listLength(struct node *r) { int *len = (int *)malloc(sizeof(int)); if(!r) { free(len); return *len; } while(r) { r = r->next; *len += 1; } free(len) return *len; } I wrote this function to calculate the length of the linked list. I am still learning pointers by playing with them....

pointed data in function with malloc keeps disappearing outside of it

c,pointers,malloc
I created two struct typedef struct node { struct node* left; struct node* right; int data; } node; typedef struct head { int count; struct node* root; } head; and here's the function that i'm trying to use to insert data into a tree. int insert(struct node* root, int value)...

Initially mallocate 0 elements to later reallocate and measure size

c,arrays,malloc,realloc
I have a function that will add a new position to an array by reallocating new memory every time it is called. The problem is that, for each call I need it to add one position to the array, starting from 1 at first call, but I understand that I...

malloc() - Does it use brk() or mmap()

c,memory-management,malloc,mmap,sbrk
c code: // program break mechanism // TLPI exercise 7-1 #include <stdio.h> #include <stdlib.h> void program_break_test() { printf("%10p\n", sbrk(0)); char *bl = malloc(1024 * 1024); printf("%x\n", sbrk(0)); free(bl); printf("%x\n", sbrk(0)); } int main(int argc, char **argv) { program_break_test(); return 0; } When compiling following code: printf("%10p\n", sbrk(0)); I get warning...

Allocating std vector content with dynamic objects

c++,malloc,std,stdvector
I have a std::vector< MyObject* > my_vector; Which is not empty and i want to allocate and push a certain amount of MyObject* in it. I know the number of objects to push. Is there a better way (optimized/faster) to do it than: int object_count = 10000; for(int index =...

Unable to properly free malloc of another malloc [duplicate]

c,malloc,free,dynamic-memory-allocation,calloc
This question already has an answer here: String assignment in C 4 answers Here's the snippet with issues. int main() { char** RESERV = (char**)malloc(sizeof(char*)*4); printf("%i, %i, %i, %i, %i", **RESERV, *RESERV, RESERV, &**RESERV, sizeof(char*)); int i; for(i = 0; i < 4; i++) { RESERV[i] = (char*)calloc(sizeof(char),16); RESERV[i][15]...

How to allocate memory to struct pointer using malloc.h header?

c,pointers,struct,malloc,dynamic-memory-allocation
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct student { char name[25]; int age; }; int main() { struct student *c; *c =(struct student)malloc(sizeof(struct student)); return 0; } What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:...

Access violation on try to fill dynamic array (large number of items)

c,arrays,pointers,malloc,dynamic-memory-allocation
I have the following C code: int dimension; double *AtS; ... AtS=(double*)malloc(sizeof(double)*dimension); for (i=0; i<dimension; i++) { AtS[i]=0.0; } While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug: Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005:...

Issue with dynamic memory allocation in C

c,malloc,dynamic-memory-allocation
I am trying to implement a sort function (counting sort, it is probably wrong): void countingsortmm(int* numbers, int len, int min, int max) { printf("Sorting %d integers with the min: %d and max: %d\n",len,min,max); int countLen = max-min+1; /* create an array to store counts for the occurences of a...

How to realloc a *char[] inside a while loop?

c,pointers,char,malloc,realloc
Let's consider this array of char pointers : char *lesMots[10]; Which is used inside a while loop : while(fgets(buffer, TAILLE_BUFFER, fichier)!=NULL){ token = strtok(buffer, s); while( token != NULL && token[0]!=13) { token[strlen(token)]='\0'; *(lesMots + ligne)=strdup(token); ligne++; token = strtok(NULL, s); } } I'm trying to reallocate the memory of...

malloc and realloc size of integer array

c,arrays,malloc
I want to be able to realloc the amount of space as my program reads in numbers. For example when running it should be able to read any number of integer and then print them out as 'Int Array: (all inputs)' This is what I have tried so far: int...

HeapValidate Fails

c,pointers,malloc,free
I'm trying to build up a structure like this typedef struct elements { struct elements *next; int key; struct value *val; }; typedef struct dict { struct dict_elements **dictionary_head; }; typedef struct value { int val; }; The structure is created like this box->dictionary_head = (struct elements**)malloc(sizeof(struct elements*) * DICT_SIZE);...

malloc doesn't allocate 3d array properly

c,arrays,pointers,compiler-errors,malloc
I am writing a program in c that would read the ppm input file and convert it to ASCII art. In the program, I alllocated a 3d array that would store the height and width of the input file and the RGB components. The array elements (pixels) would then be...

C: Why does snprintf only writes 4 characters to my variable?

c,printf,malloc
So I'm trying to return a variable that contains a string with some parameters determined inside the function. char* render(my parameters) I'm declaring my variable like this: char *string = malloc(sizeof(char) * 50); This is an excerpt of my function: switch(INST_OPCODE){ case 0x00: inst->name = malloc(sizeof(char) * (strlen("add") + 1));...

shallow copy struct got weird result on Xcode

c,malloc,free,dynamic-memory-allocation,shallow-copy
the code here is a typical example for shallow copy, it ought to got the warning when running, but on my Xcode, its running well and result is hi,hihi,hi why? The code: struct pc { char *p; }; int main() { struct pc pc1; pc1.p = malloc(100); strcpy(pc1.p, "hi"); struct...

Dynamic Memory Allocation

c,malloc,dynamic-memory-allocation
How malloc() stores metadata? void* p; void* q; p = malloc(sizeof(char)); q = malloc(sizeof(int)); I know that the return value p[0] points to the start of allocated block of memory, than if I iterate and print p[-1], p[-2].... q[-1], q[-2].... or p[1], p[2], p[3], p[4].... or q[1], q[2], q[3], q[4].......

Free list implementation not working properly

c,malloc,free
So, I have been assigned a task to implement a free list. A list where items that are going to be free:d are added to and later the list is free:d in one go. I have written the following: #include <assert.h> #include <stdio.h> #include <stdlib.h> typedef struct list_t list_t; struct...

C array of structs segmentation fault

c,arrays,pointers,struct,malloc
I am trying to make a dynamic array of structs, and I can successfully add one struct to it. But any more structs I add cause a segmentation fault. Here is my code: #include <stdio.h> #include <stdlib.h> #include <string.h> #define PEOPLE_BLOCK 4 struct Person { char *first_name; char *last_name; unsigned...

Why is _stprintf_s overwriting other variables but _stprintf is not?

c++,winapi,printf,malloc
I'm using visual studio for win32 programming class. I have a global array of string declared as TCHAR **bufTh allocated in memory like bufTh = (TCHAR**)malloc(nOfTh*sizeof(TCHAR*)); for (i = 0; i < nOfTh; i++) bufTh[i] = (TCHAR*)malloc(BUF_LEN*sizeof(TCHAR)); then I have some threads, each of them writing on a different string...

How to check if memory is available for read/write operation?

c,windows,multithreading,visual-studio-2010,malloc
I am trying to write character values in a memory which I define using malloc() and simultaneously read a character value from it. For this I define the memory globally and then start a thread. In thread I am writing character value in memory and In main() I am reading...

Initialization of Class using malloc()

c++,c,lua,malloc,new-operator
How should a c++ class be used when its memory has been reserved from a C malloc? I'm using a C library (lua) and I need to expose a C++ class to it, in this case in order to garbage collect these reserved space, lua does the memory reservation. A...

Calling free() causes my program to crash

c,crash,printf,malloc,free
I'm having a really weird issue where trying to call free on an allocated piece of memory causes my program to crash. Here's the relevant code: int i, count; char *specifier; char aisle[1]; count = 0; /*Find name of the new item and assign to the name field of new_node...*/...

Pointing to an array inside a struct that is inside another struct

c,arrays,struct,malloc,dynamic-memory-allocation
How can I access an array / other type of data that is inside of a struct which is inside of another struct. This is what Ive tried so far and its coming out as c is not declared. I know I can declare c as prod_t *c but it...

microcontroller fails at malloc

c,pointers,malloc,microcontroller
I am writing a function on a 32-bit cortex m4 microcontroller. The function has to be able to multiply matrices of different sizes, which I cannot predict. So i Have to use a malloc... But I don't understand why my mc always goes into default handler interrupt when it executes...

How can I change maximum available heap size for a task in FreeRTOS

embedded,malloc,heap,keil,freertos
I'm creating a list of elements inside a task in the following way: l = (dllist*)pvPortMalloc(sizeof(dllist)); dllist is 32 byte big. My embedded system has 60kB SRAM so I expected my 200 element list can be handled easily by the system. I found out that after allocating space for 8...

Accessing char array inside struct showing out of bounds error

c,arrays,struct,malloc,dynamic-memory-allocation
I have the following C struct and using the function getPerson(void) that returns a pointer to my struct returns a pointer to a new struct using user input. The following code does not compile and it gives the following error: #include <stdio.h> #include <stdlib.h> typedef struct { char name[50]; int...

c - getting a heap error when trying to free

c,pointers,malloc,free,strcat
This smells like a heap corruption of some kind but I can not seem to find it. the problem occurs on string_utils_replace() when trying to run free(tmp_for_free). the function is supposed to replace every occurrence of "search" with "replace" in "string". char* string_utils_part_of_string(char *string, int from, int to) { int...

c++ unsigned char array allocation - segmentation fault

c,segmentation-fault,malloc,memset,unsigned-char
I can't figure out what seems to be the problem that I get a segmentation fault from this: #include <stdio.h> #include <stdlib.h> #include <cstring> void alloc(unsigned char *data) { data = (unsigned char *) malloc(20); memset(data, 0, 20); } void main() { unsigned char *data = NULL; int i; alloc(data);...

C - Program crashes while using malloc

c,crash,malloc,xor-linkedlist
So I'm making a XOR linked list, and whenever I'm trying to allocate memory for a new node, program crashes. Here's my code for insert function: void add(DataType value, XORList ** xlist) { XORListNode * node; node = ( XORListNode* )malloc( sizeof (XORListNode) ); printf("node memory allocated\n"); if ((*xlist)->head->prevPNext ==...

Call to malloc() causes unexplicable program crash

c,string,segmentation-fault,malloc,dynamic-memory-allocation
I'm having an issue where a call I'm making to malloc() causes my program to crash. Here's the code: void update_item(char *input, item_t *new_node){ int i, count, shelf, weight, price, quantity; char *name; char *specifier; char aisle[1]; count = 0; /*Find name of the new item and assign to the...

Char arrays filled with 0xCC after allocation [duplicate]

c++,malloc
This question already has an answer here: When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete? 8 answers So after allocating char array in debugging windows I can see my array is filled with 0xCC. What does it mean? (-52 = 0xCC)...

Debug error: Heap corruption detected

c,visual-studio-2010,pointers,malloc
I am playing around a bit in C and trying to write a test program for kind of oop in c programming. I get the Error of the headline in Visual Studio 2010. In using gcc i don't get this error. Can anyone point me to what i am doing...

Predefined string segfaults when copied to by strncpy()

c,segmentation-fault,malloc,strncpy
Why is it that ... char *dst = (char*) malloc(sizeof(char) * 11); char *src = "ABCDEFGHIJKLMNOPQRSTUVQXYZ"; strncpy(dst, src, 10); ... works fine, but ... char *dst = "ABCDEFGHIJ\0"; char *src = "ABCDEFGHIJKLMNOPQRSTUVQXYZ\0"; strncpy(dst, src, 10); ... or even ... char *dst = "ABCDEFGHIJ\0"; char *src = "KLMNOPQRST\0"; strncpy(dst, src, 10);...

How can I deallocate my memory? [duplicate]

c,malloc,free
This question already has an answer here: How will you free the memory allocated? 2 answers I'm using malloc and I should do free but I'm a beginner in C and I didn't write a call to free before. This is the code if((new_str = malloc(strlen(token2)+strlen("/less")+1)) != NULL) {...

Allocating space for upper triangular matrices in algebraic notation

c,matrix,malloc,free,algebra
I'm working on a project (written in C) involving matrix factorization and I need some help. My objective is to allocate memory for an upper triangular matrix and I want to access it via algebraic row and column notation (i.e. i,j in {1,2,...,n} instead of i,j in {0,1,...,n-1}). For example,...

How to initialize a 3d array in C - Array of arrays of pointers

c,arrays,pointers,malloc
I am programming a game which generates the next possible moves. I need to generate the next moves in order to perform the search. However I have no idea about how to do it in C. The code to generate the board is: #include <stdio.h> //prints #include <stdbool.h> //bool #include...

C - Why is a fixed size array performing much slower than a dynamically allocated array?

c,arrays,malloc
I have a csv with over 4M lines that I'm loading into an array. csv: EURUSD,20010102,230100,0.9507,0.9507,0.9507,0.9507,4 This operation takes about 3.5 minutes. ... typedef struct Rates_t { char open[7]; char high[7]; char low[7]; char close[7]; } Rates_t; void Substr(char *src, char **dst, int start, int length) { char *ptr1 =...

Segmentation fault when trying to allocate memory for a string via a pointer-to-pointer function call

c,pointers,file-io,segmentation-fault,malloc
I Initiate my string and call my function like this: int main() { ... char *fileBuffer; readFileToBuffer("/tmp/file.txt", &fileBuffer); ... } The purpose of this function is to get the contents of file.txt and put it into the fileBuffer variable. Because the content of file.txt is dynamic, I allocate the memory...

Deallocating 2D array in C

c,arrays,malloc,free
For whatever reason I am getting the following error when trying to free the 2D array I created: Error in `./a.out': free(): invalid next size (fast): 0x0000000001759310 *** Aborted (core dumped) I printed out the contents of the array and they are correct and I am able access all of...

valgrind error Invalid read of size 8

c,memory-leaks,malloc,valgrind
So I have valgrind complaining with this error in this function: int getMembersNum(Party party){ assert(party != NULL); int i = 0; while (party->members[i] != NULL && i < party->maxMembersNum) <-- HERE i++; return i; } Party is a pointer to a struct and party->members is of type char**. When initialized...

C dynamic allocation of a 2D array in a function & return pointer

c,arrays,malloc
I would like to call a function with some arguments and within this function allocate a 2D array and then pass the pointer to it back to main. this is not the actual code I'm using but a simplified "toy" code to explain what I'm trying. I am getting a...

Is setting environment variable through a makefile - possible?

c,unix,makefile,malloc,gnu-make
I'd like to take advantage of MALLOC_PERTURB_ environment variables that can change memory allocation parameters (man 3 mallopt). However, I'd like to control allocation parameters on application level, not entire system level. Ideally, if I could control them through project's makefile. I've tried to change mentioned variables through makefile, yet,...

malloc can't create space for struct in queue

c,struct,queue,malloc
I tried to create a queue which contains 2 int values. The problem happens in insert function. When i try to allocate memory for head->front->next program halts. The error happens only in else part in insert function. struct Patient{ int national_id; int condition; }; struct Node{ struct Patient *info; struct...

size of array allocated with malloc is showing one less than expected

c,arrays,pointers,malloc,sizeof
I have this: alloc(Btree *bt, uint8_t *keylen, int16_t n) { bt->node[n].key = malloc(sizeof(int16_t)*(*keylen)); { Where bt->node[n].key is a pointer to int16_t. With the debugger running, I can verify that keylen is 5. But if I put: int kl = sizeof(bt->node[n].key) / sizeof(bt->node[n].key[0]) kl is 4. What did I do wrong?...

Realloc an array but do not lose the elements in it

c,pointers,malloc,realloc
Code: int * data; data = malloc(sizeof(int)*10); int i; for(i=0;i<10;i++) data[i]=i; int * aux; aux = realloc(data,sizeof(int)*20); if(aux) data=aux; for(i=10;i<20;i++) data[i]=i; A teacher once told me "No, you can't reallocate an array with elements without a backup"; I said, "Oh, OK", but now that make no sense to me. The...

How to use 'new' instead of 'malloc' to allocate a 2D-array, dynamically?

c++,pointers,multidimensional-array,malloc
I'd like to make matrix using 2-D pointer. There was no problem when I used 'malloc' and 'free' functions for memory use (see my code). However, I couldn't write the same code using 'new' and 'delete'. As you know, 1-D pointer can be declared by 'new'. For example, double *example...

Storing return values (void pointers) from malloc

c,pointers,memory-management,malloc,void-pointers
How should I store the pointers returned from malloc? I have a small parser that allows nested includes in the source files, meaning the first source file can include foo, then foo can include bar and so on. This feature forces me to keep the memory allocated to each file...

Getting input into dynamically allocated memory then returning the pointer

c,arrays,pointers,malloc
Hey guys i've been having some problems with this problem. I have tried it many ways from looping with stdin and saving each letter to scanf(" %s") into an array then declaring the array as a pointer then returning the pointer. I have come close but have mainly had problems...

Input returns the correct string but doesn't run the function

c,string,malloc,getline,strlen
I have the following code: bool get_command(char *cmd){ char *cm = (char*)malloc(strlen(cmd)); strcpy(cm,cmd); const char *tok = strtok(cm," "); if(!tok) return false; if(!strcmp(tok,"MULTIPLY")) { printf("WORKING!\n"); return true } .... int main(void){ while(1){ char *input = NULL; char buf[MAX_LINE_LENGTH] = {0}; int read; size_t len; read = getline(&input, &len, stdin); if...

C - malloc - invalid conversion from void* to double*

c,malloc
I want to write a function that creates a copy of a double array using pointers. This is my code so far: #include <stdio.h> #include <stdlib.h> double* copy (double *array, int size) { double *v=malloc(sizeof(double)*size); for (int i=0; i<size; i++) *(v+i)=*(array+i); return v; } int main () { //double array[];...

Why is my string truncated when copied?

c,string,pointers,malloc,sizeof
I'm trying to find whether less is installed using C (with no use of system calls). But there is something wrong with my copying of the variable. The contents of the string is truncated: int ret; char * pathValue; char * pathValue2; char *token3; char * new_str ; int pathlength;...

Malloc confusion

c,pointers,malloc
Hi after going through answer here 1: Do I cast the result of malloc? I understood that one of the reason why we do not cast malloc is that casting malloc is redundant But what I am still trying to figure out is the warning that will be suppressed when...

Malloc'ing pointer-to-pointer member of struct

c,pointers,struct,malloc,dynamic-memory-allocation
I'm trying to use a structure to hold a pointer to a data block that I change sometimes when a file is updated, the idea being to free the old data block, malloc a new one of the right size, and assign the pointer to pointer in the structure to...

Dynamically creating a 2D array of pointers using malloc in C

c,arrays,pointers,malloc
This is a structure that I am using: struct nodeList//a node structure { int jump; int config; int level; int shifts[200]; int shift_diff[200]; struct nodeList *next; }; I want to create a 2D array of pointers that can be used to reference such a structure variable, ie, any element of...

C issue with dynamically allocating array

c,arrays,malloc
The input file for my program has the first line containing an int (call it N) that will signify how many following integers there will be (each integer on a new line). Then it should read the integers into num_array and print them out. My issue is that num_array is...

Proper usage of malloc() and free() in c

c,malloc
I'm new to C so forgive me if this is too obvious, but I am having an issue finding the error in my code that is leading to a segmentation fault. I believe the issue may be in the usage of malloc(), but I am not positive. Here is the...

Does C++ runtime always require malloc()?

c++,malloc,xilinx,standard-library,bare-metal
I have a C++ application running bare-metal that I want to make as small as possible. I am not using dynamic memory allocation anywhere. I am using no STL functions. I've also overridden all the varieties of "delete" and "new" with empty functions. Nonetheless, when I look at a sorted...

correct use of malloc in function with passed uint32_t array pointer

c,malloc,uint32-t
I'm having difficulty using malloc in a function where I read a binary file with 4 byte unsigned integers, free the passed array reference, remalloc it to the new size and then try to access members of the array. I think the problem is due to the uint32_t type as...

17653 Segmentation fault (core dumped)

pointers,malloc,openmp,double-pointer
I am trying implement a matrix multiplication with dynamic memory allocation with OpenMP. I manage to get my program to compile fine but when i am trying to execute it i am getting ./ line 14: 17653 Segmentation fault (core dumped) ./matrix.exe $matrix_size int main(int argc, char *argv[]){ if(argc <...

Dynamic Memory Allocation to Reverse Print Array of Floating Point Numbers

c,arrays,struct,floating-point,malloc
So I'm brand new to C and playing around with memory allocation for arrays. I'm trying to create a program that will dynamically allocate space using malloc to reverse an array of floating point numbers. #include <stdio.h> #include <stdlib.h> struct Rec { float * x; int size; }; int main(){...

Difference between malloc() and simple declaration in fixed sizes [duplicate]

c,double,malloc,difference
This question already has an answer here: Difference between declaration and malloc 8 answers Let assume that I want to get space for an array of x double, x being an integer. Can someone explain me the difference between double myArray[x]; and malloc(x*sizeof(double)); excepted the fact that malloc() returns...

C - strcpy with malloc size less than argument's size [duplicate]

c,malloc,strcpy
This question already has an answer here: I can use more memory than how much I've allocated with malloc(), why? 15 answers char* init_array() { const int size = 5; char *p = (char*) malloc(size * sizeof(char)); strcpy(p, "Hello, world! How are you?"); return p; } with size =...

Confusion with realloc in C language [duplicate]

c,malloc,realloc
This question already has an answer here: Why can I still access a member of a struct after the pointer to it is freed? 6 answers I have a code like this : void **array = (void**)malloc(sizeof(void*)*4); array[0] = (void *)"Hello"; array[1] = (void *)"World"; array[2] = (void *)"My";...

malloc and realloc array giving unexpected output

c,arrays,malloc,realloc
When input is '1 2 3 4 5 6 7 8 9 10 11' Expected output should be the same as input. Yet the output is '1 2 3 4 5 6 7 8 9 10 -1850774484' . Only happens when there are more than 10 integers being inputted. Where...

Changing the size of a global array in the main function

c,list,struct,malloc
I am writing a program that needs to create a variable number of linked lists. The following is declared globally at the beginning of the program: struct Node { int Line; struct Node *Next; } ; struct Node* Heads[5]; struct Node* Currs[5]; int NumOfNames; The first function in main() will...

Does C have a shorthand way of initialize a struct with malloc and set its fields?

c,data-structures,struct,initialization,malloc
I have a messy block of code like result = (node*)malloc(sizeof(node)); result->fx = (char*)malloc(sizeof(char) * 2); result->fx[0]='x'; result->fx[1]='\0'; result->gx = NULL; result->op = NULL; result->hx = NULL; where I initialize an element of type typedef struct node { char * fx; // function struct node * gx; // left-hand side...

Why does the memory not allocate?

c,arrays,memory,malloc,word
My assignment is to allow the user to enter any input and print the occurrences of letters and words. We also have to print out how many one letter, two, three, etc.. letter words are in the string. The word function has an access violation when dealing the array of...

size of a node in linked list

c++,malloc,sizeof
Program: #include <iostream> #include <stdlib.h> using namespace std; struct node { int data; struct node *next; }; int main() { struct node* head = NULL; head = (struct node*)malloc(sizeof(struct node)); cout<<sizeof(struct node)<<"\n"<<sizeof(head)<<"\n"<<sizeof(int); return 0; } Output: 8 4 4 Why is sizeof(struct node) different than sizeof(head) ? Wouldn't have malloc...

Garbage with strcpy and strcat

c,malloc,strcpy,strcat
I'm doing a client-server project in linux and I need to concatenate some strings. I tried my code on visual studio in windows and it works fine, but it linux it gives me some garbage. I've got this function: char* concat(char s1[], char s2[]) { int tam = 0; tam...

free causing different results from malloc

c,string,malloc,free
Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free
I am writing a program that is sorting the lines from the input text file. It does its job, however I get memory leaks using valgrind. #include <stdio.h> #include <stdlib.h> #include <string.h> char* getline(FILE * infile) { int size = 1024; char * line = (char*)malloc(size); int temp; int i=0;...

pointer being realloced was not allocated

c,malloc,realloc
I am trying to dynamically allocate an array of structs but whenever I run the program I keep getting: a.out(6487,0x7fff7ecb8300) malloc: * error for object 0x7fff6f670000: pointer being realloc'd was not allocated * set a breakpoint in malloc_error_break to debug struct node { char course[25]; char category[20]; char prereq[50]; char...