SIGABRT error during alllocation of char array [closed] - c

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...

Related

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).

SIGTRAP when calling the free() function

I'm getting a SIGTRAP signal when trying to free an dynamically created array, and have no idea on why.
I'm allocating the array like this:
int* visited = (int*) malloc( l.nodeCount * sizeof(int));
(l.nodeCount is an integer. In the instance of the program I get this error, it is set to 12.)
And when I try to free(visited), I get the SIGTRAP signal in the debugger.
The whole function is this one:
int Graph_GetSmallestPathCount(AdjacencyList l, int destination){
//One path if destination is root
if(destination == 0) return 1;
if(l.nodeCount == 0)
return 0;
Queue reading = Queue_NewQueue();
Queue storing = Queue_NewQueue();
/*Allocates visited array*/
int* visited = (int*) calloc( l.nodeCount, sizeof(int));
/*Visited array initialization*/
int i;
for(i = 0; i < l.nodeCount; i++)
visited[i] = 0;
/*Marks root node and enqueues it*/
visited[0] = 1;
Queue_Enqueue(&reading, 0);
//While there are nodes to read
while(!Queue_IsEmpty(reading))
{
//Dequeues a node
int v = Queue_Dequeue(&reading);
//Gets it's adjacency list
List* currentList = AdjacencyList_GetAdjacentNodes(l, v);
listCell* auxCell = currentList->head->next;
//While there are nodes in it's adjacency list
while(auxCell != NULL){
//Enqueues it if it has not been visited
if(visited[auxCell->data] == 0){
Queue_Enqueue(&storing, auxCell->data);
}
//Adds to the paths to that node
visited[auxCell->data] += visited[v];
auxCell = auxCell->next;
}
//When the queue ends
if(Queue_IsEmpty(reading)){
//If the destination has been reached, return
if(visited[destination] > 0){
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return visited[destination];
}
else{
//Switch queues
Queue_Destroy(&reading);
reading = storing;
storing = Queue_NewQueue();
}
}
}
//Destination has not been reached before end of algorithms. Deallocate everything and return 0
free(visited);
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return 0;
}
Sorry for the lack of comments, I did this on a run and didn't put any in. Also sorry for the printf overload, I put them there while trying to pinpoint the problem.
EDIT: I cleaned it up a little.
The weird thing is that the program works for certain inputs and doesn't for others.
Hope someone can help me out =D
I can't tell you why you get a SIGTRAP as you haven't published a minimal example.
However, I can tell you how to find out out yourself:
Make your program readable. Use one instruction per line. The indent tool is your friend. Sure, that won't fix the bug, but it will make it easier for you to find it.
Don't malloc like that. There is no need to cast the return value of malloc, and using calloc(l.nodeCount, sizeof (int)); or similar is more readable anyway.
What SIGTRAP actually means is you've hit a breakpoint instruction. No doubt what's actually happening is that you've jumped to something which is not your code, and might not be code at all, but contains the binary code for a breakpoint. Why did that happen? The normal cause would be memory corruption, particularly stack corruption. I'm guessing free() is corrupting its own stack. And I'd guess the reason for that is because you are (somewhere) writing to memory outside the memory you've allocated. To test this, run your program with the malloc()/calloc() immediately followed by the free() and an exit(0). If that works, you know the issue is something you are doing between.
We can't tell what you are doing between because you haven't (thankfully) posted the full program, but try running it under valgrind. When you get an out-of-range write, valgrind will normally pick it up. Fix every valgrind warning. That doesn't guarantee a solution, but will find one 95% of the time in my experience.
Also note that return visited[destination]; appears to exit the function without free()-ing visited, which is thus a memory leak.
First, don't call malloc() like that. l.nodeCount * sizeof(int) could potentially exceed INT_MAX, and you'll either have a security hole or if you're lucky, a crash.
Instead, use calloc(l.nodeCount, sizeof(int)).
You should also check the return value of malloc or calloc for NULL in the event your program runs out of memory to allocate.
Found the answer. There was indeed a chance that on specific cases the array would be created with one element less than it should. My bad.
Thanks to all who helped =D

Dynamically reallocating an array of structs in C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
A part of my code will read in an unknown number of lines from a text file, parse that line into a structure (tempSomeStruct), resize the SomeStruct_Array, and then add that tempSomeStruct into the newly opened spot in memory.
However after a few times through the while loop, my program stops and says
myApplication.exe has triggered a breakpoint.
I did not set a breakpoint, and doing some digging, it LOOKS like the breakpoint is due to heap corruption from my call to realloc. I am pretty new to dynamic allocation, so while I have searched and found a few possible causes, so far no fixes have worked.
How am I corrupting the heap in this situation, and what do I do differently to avoid doing so?
I have a function like this:
int growArray(SomeStruct **SomeStruct_Array,int currentSize, int numNewElements)
{
const int totalSize = currentSize + numNewElements;
SomeStruct *temp = (SomeStruct*)realloc(*SomeStruct_Array,(totalSize * sizeof(SomeStruct)));
if (temp == NULL)
{
printf("Cannot allocate more memory.\n");
return 0;
}
else
{
*SomeStruct_Array = temp;
}
return totalSize;
}
and it is called in elsewhere like this:
SomeStruct* SomeStruct_Array = (SomeStruct *) calloc(1,sizeof(SomeStruct));
int Error_Array_Size = 0;
if(SomeStruct_Array == NULL)
{
printf("Cannot allocate initial memory for data\n");
return;
}
while(fgets(line,sizeof(line), file) != NULL)
{
parseTextIntoSomeStruct(line, &tempSomeStruct);
SomeStruct_Array_Size = growArray(&SomeStruct_Array,SomeStruct_Array_Size,1);
if(SomeStruct_Array_Size > 0)
{
SomeStruct_Array[SomeStruct_Array_Size] = tempSomeStruct;
}
}
Your new array's size is SomeStruct_Array_Size, and you immediately write to SomeStruct_Array[SomeStruct_Array_Size] which is one past the end of the array! Remember, C arrays are zero-indexed.
Use
SomeStruct_Array[SomeStruct_Array_Size-1] = tempSomeStruct;
instead.

how check null pointer in c programming , get this compile error: used struct type value where scalar is required , [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
struct s_client *cur_client(void){
return (struct s_client *) pthread_getspecific(getclient);
}
int32_t chk_process (int32_t) {
...
struct s_client *ptr = cur_client();
//FIXME
// how could i check in this line , just when the value of
// ptr is not zero , then it goes to it's next line?`
send_data (ptr, index);
...
...
}
i would like to check , only at the time that the value of ptr , is not zero , it goes to it's next line , i tried this line of code
if (*ptr != 0)
but as expected this wasn't correct , since it's not check the value !
Edit2 :
Well , i found myself the reason , since ptr fullfilled from pthread_getspecific . If pthread_getspecific is called on the key whose thread specific data is being destroyed, the value NULL is returned. For more info , u could check the man page ... End of the story
Edit1 :
Well This is the struct name cur_client() , which is use in above codes
You probably wanted to test if the pointer was not null. If so, you shouldn't dereference it when making the comparison:
if (ptr != 0)
Or:
if (ptr != NULL)
ptr is a pointer to struct s_client, whereas *ptr is the struct s_client itself.
You're not comparing the pointer to 0, you're trying to compare the structure to 0, which can't be done.
It seems that you want to check whether the struct that is pointed to by the pointer contains zeroes only. You can do it like this:
int i, isNonzero = 0;
for (i = 0; i < sizeof(*ptr); i++) {
if (((char *)ptr)[i] != 0) {
isNonzero = 1;
break;
}
}
if (isNonzero) {
/* etc. */
}
Edit: no, ptr is not the address of the pointer, it's the pointer itself. Compare it to NULL if you want to check that. A pointer is just a normal variable itself that holds an integer representing a memory address. A pointer-typed variable (which ptr is) has an address itself, which it seems you think gets compared when you use the != operator. No, it doesn't - you would have to write
if (&ptr != NULL) {
}
for doing that. Don't worry, other answers' suggestions are also good.
And please, make the effort to read a tutorial on C pointers. This is something too basic to be asked on StackOverflow.

c free() function question [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C programming : How does free know how much to free?
Hi,
when i have following code:
void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);
how does the free() function know how much space has to be freed?
thank you!
--
ok i have found other questions asking the same, please close - sorry
This information is usually contained in some memory area managed by the malloc implementation. The information often preceeds the actual memory handed out to you by malloc, but that's an implementation detail, and you cannot rely on anything here.
It's implementation dependent but usually the underlying system mas a map of addresses to blocks and it knows the size from that memory map.
Here is the striped down code from glibc which shows it doing basically what what I just said.
void fREe(Void_t* mem)
{
arena *ar_ptr;
mchunkptr p;
if (__free_hook != NULL) {
(*__free_hook)(mem, NULL);
}
if (mem == 0) /* free(0) has no effect */
return;
p = mem2chunk(mem);
if (chunk_is_mmapped(p)) /* release mmapped memory. */
{
munmap_chunk(p);
return;
}
ar_ptr = arena_for_ptr(p);
chunk_free(ar_ptr, p);
(void)mutex_unlock(&ar_ptr->mutex);
}

Resources