How should i fix the Warning C6308 ' [duplicate] - c

This question already has answers here:
Error C6308 happens when I compile this code, saying realloc can return NULL, and may cause memory leak
(1 answer)
realloc does not work when shrinking block, only when expanding [closed]
(1 answer)
Closed 2 months ago.
im getting an warning message which says. Warning C6308 'realloc' might return null pointer: assigning null pointer to '*destination', which is passed as an argument to 'realloc', will cause the original memory block to be leaked. and im wondering if some of you could help me to fix this problem.
My code:
void dstring_truncate(DString* destination, unsigned int truncatedLength)
{
assert(destination != NULL);
assert(*destination != NULL);
assert(truncatedLength >= 0);
*destination = realloc(*destination, truncatedLength + 1); // +1 för nollterminatorn
if (*destination == NULL) {
fprintf(stderr, "Memory allocation faild\n");
}
}

Related

Function can not allocate memory for a pointer in C [duplicate]

This question already has answers here:
How do I modify a pointer that has been passed into a function in C?
(7 answers)
Closed 3 years ago.
I have a struct which is called "visitor" and I want to write function which allocates the memory for my pointer to this struct ...
this Codes works:
visitor *visitorPtr = NULL;
int visitorCounter = 0;
visitorPtr = realloc(visitorPtr, ((visitorCounter++) * sizeof(visitor)));
but now I wanted to put this functionality to a function
void getMoreSpace(void *ptr, unsigned int counter)
{
counter++;
ptr = realloc(ptr, counter * sizeof(visitor));
if (ptr == NULL)
{
printf("\n Error allocating memory! \n");
return EXIT_FAILURE;
}
}
//Call in MAIN:
getMoreSpace(visitorPtr, visitorCounter);
Unfortunately it seems not to work because I cant create data for this pointer and get this Error when I make that for that struct:
Exception thrown at 0x0FDAE559 (ucrtbased.dll) in My-C-Project.exe: 0xC0000005: Access violation writing location 0x00000000.
visitorPtr is passed as value to getMoreSpace function. Thus any changes done to ptr within the function will not update the vistorPtr in main.
What you need is call the function by reference as below.
void getMoreSpace(void **ptr, unsigned int counter)
{
counter++;
*ptr = realloc(*ptr, counter * sizeof(visitor));
if (*ptr == NULL)
{
printf("\n Error allocating memory! \n");
}
}
And from main you call as below.
getMoreSpace(&visitorPtr, visitorCounter);
if (visitorPtr)
...do stuff....

Why pointer is not null after free() (no copy pointer) [duplicate]

This question already has answers here:
C - pointer is not null after freeing it
(6 answers)
Why doesn't free(p) set p to NULL?
(9 answers)
Closed 4 years ago.
I use only main() function. Not copying any pointer.
Why free() function not get NULL value?
Whay I can check my wariable is full or empty?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *e = NULL;
printf("before e=%p\n",(void *)e);
e = malloc(sizeof(int));
*e = 7;
printf("after, e=%p\n",(void *)e);
if(e == NULL) { printf("Problemy z pamięcia\n"); return 0; }
printf(" value = %d\n",*e);
free(e);
printf("after free, e=%p\n",(void *)e);
if(e == NULL) printf("is NULL\n");
return 1;
}
result
before e=0
after, e=464027a0
value = 7
after free, e=0x7f82464027a0
why if(e==NULL) is not true? How do it?
Because C has a call-by-value policy and free is a standard function. Every function call is not modifying its arguments, because formal parameters hold a copy of the argument passed at the call.
In practice, you could use the comma operator and systematically do
free(e), e = NULL;
However, using a pointer (value) after it has been free-d is undefined behavior. Be scared of UB, so learn more about it.
You should compile with all warnings and debug info (so gcc -Wall -Wextra -g if using GCC) and learn to use the gdb debugger. You could use tools like valgrind or address sanitizers, since they are very helpful to hunt bugs such as memory leaks or buffer overflows.
BTW, your code is wrong. You don't test against failure of malloc (your if(e == NULL) is too late, and the preceding *e = 7; is likely to get a segmentation fault when malloc has failed) , and you really should code at least something like:
e = malloc(sizeof(int));
if (!e) { perror("malloc e"); exit(EXIT_FAILURE); };
The !e above could be replaced by e==NULL for readability.

C - Why does returning an int result in a segmentation fault? [duplicate]

This question already has answers here:
Malloc, free and segmentation fault
(4 answers)
Closed 6 years ago.
I'm working on a small private project that reads some links from an html-page source. I read the html file line by line and then check if that line contains "data-cfsrc", which always preceeds a link that I want to read. This works fine, until I try to free the pointer that points to where the keyword ("data-cfsrc") starts.
I've tried freeing it on multiple points and it only works when I haven't done anything with it yet.
Here's my code:
FILE *fp_w, *fp_r;
fp_r = fopen("page.html","r");
fp_w = fopen("bg_list.txt","a");
char line[1024],img[512],c;
//char *imgpoint = malloc(sizeof(char)*512);
char *imgpoint;
int i,imgcount = 0;
while(imgcount<15){
// read line
i = 0;
do{
c = fgetc(fp_r);
line[i] = c;
i++;
}while(c!='\n');
line[i] = '\0';
if(strstr(line,"data-cfsrc") != NULL){
imgpoint = strstr(line,"data-cfsrc");
strcpy(img,imgpoint);
c = 0;
for(i=0; c!=34; i++){
img[i] = img[i+12];
c = img[i+13];
}
img[i] = '\0';
fprintf(fp_w,"%s\n",img);
imgcount++;
printf("imgcount = %d\n",imgcount);
}
}
fclose(fp_r);
fclose(fp_w);
//free(imgpoint);
return 0;
EDIT: as mentioned, I removed the free() entirely, but now my program still results in a Segmentation fault when return is called.
EDIT 2: completely ommitted the impoint pointer. Everything still works, but I still get a Segmentation fault on return.
free() requires you to pass the same pointer that was returned by malloc() (or friends). But here,
imgpoint = strstr(line,"data-cfsrc");
you are reassigning it. Hence undefined behaviour when free() is called.
From free():
The free() function frees the memory space pointed to by ptr, which
must have been returned by a previous call to malloc(), calloc(), or
realloc(). Otherwise, or if free(ptr) has already been called
before, undefined behavior occurs. If ptr is NULL, no operation is
performed.
(emphasis added).

Increase the maximum size of char array [duplicate]

This question already has answers here:
Getting a stack overflow exception when declaring a large array
(8 answers)
Closed 4 years ago.
I have written some code in C by taking the maximum size of char array as 100. It worked well. But when I increase the maximum size of char array to 10000 it gives me segmentation fault(as it has exceeded its limit). Can someone tell me how can I increase the maximum size and store a string of length 10000.
i.e How can I take the "char a[100]" as "char a[10000]" and execute the same code????
You can allocate the array dynamically:
#include <stdlib.h>
char *a = malloc(100*sizeof(char));
if (a == NULL)
{
// error handling
printf("The allocation of array a has failed");
exit(-1);
}
and when you want to increase its size:
tmp_a = realloc(a, 10000*sizeof(char));
if ( tmp_a == NULL ) // realloc has failed
{
// error handling
printf("The re-allocation of array a has failed");
free(a);
exit(-2);
}
else //realloc was successful
{
a = tmp_a;
}
Eventually, remember to free the allocated memory, when the array is not needed anymore:
free(a);
Basically realloc(prt, size) returns a pointer to a new memory block that has the size specified by size and deallocates the block pointed to by ptr. If it fails, the original memory block is not deallocated.
Please read here and here for further info.

SIGABRT error during alllocation of char array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
My program crashes on following piece od code:
newElement->name = (char*) malloc((strlen(name) + 1) * sizeof(char));
By using debugger I get SIGABRT error and I don't know why because it stops during second iteration (first iteration goes without any problem).
I checked if
name
has a treminating null character and it has.
Here is whole code:
element* createElement(const char* name, const char* text) {
if (name == NULL) return NULL;
element* newElement = malloc(sizeof(element));
if (newElement == NULL) return NULL;
newElement->name = (char*) malloc((strlen(name) + 1) * sizeof(char));
if (newElement->name == NULL) return NULL;
strcpy(newElement->name, name);
if (text == NULL) newElement->text = NULL;
else
{
newElement->text = malloc((strlen(text) + 1) * sizeof(char));
if (newElement->text == NULL) return NULL;
strcpy(newElement->text, text);
}
newElement->parentNode = NULL;
newElement->previousSibling = NULL;
newElement->nextSibling = NULL;
newElement->firstChild = NULL;
newElement->lastChild = NULL;
return newElement;
}
From
http://linux.die.net/man/3/malloc
If MALLOC_CHECK_ is set to 0, any detected heap corruption is
silently ignored; if set to 1, a diagnostic message is printed on
stderr; if set to 2, abort(3) is called immediately; if set to 3, a
diagnostic message is printed on stderr and the program is aborted.
So you're getting a SIGABRT because you have MALLOC_CHECK_ set to 2 or 3. If it's 2, change it to 3 to get a diagnostic message.
Your code by itself is totally fine.
The sigabort may result from a heap overflow, i.e., you run out of memory for your malloc.
You're trying to malloc a certain portion of memory given by the expression:
(strlen(name) + 1) * sizeof(char)
Probably you problem is with the strlen(name) part.
Maybe name doesn't have a null terminated string and therefore strlen doesn't work.
As pointed out in the comment's the malloc itself isn't supposed to create and heap overflow but, it may indeed call abort() if it detects some internal data corruption which may and probably are caused by and heap overflow, buffer overflow or a leak in any other part of the code not directly related to this code. The important thing here is: does this malloc call return? or does it send the signal during execution?
If it doesn't return and it sends SIGABRT during execution you may have an hard time trying to figure out where in your program have you corrupted data structures necessary for malloc... If you're saying that the first malloc call you do executes with no problem maybe you should look at what code is executed in between but I believe that you can't be sure about the corruption happening in between the two malloc calls, malloc may simply don't see the corruption at the first execution for various reasons...

Resources