Re: kernel memory issue using malloc()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Mounir Bakkali wrote:
> Hi everything,
>
> Here is the issue:
> I am trying to allocate some memory for my data structure
> and after a msecs, I get a "segmentation fault" right after
> "allocating mem"....
> but if I change the size of the malloc from 256 to 512, it works just
> fine.
>
> My guess is that somehow, internal there is a segmentation fault but not
> in that peace of code but in another peace of code and that I get a
> segmentation
> fault only when I call malloc only when I try to allocate the memory....
>
> I have checked the memory and it looks fine (lots of mem still
> available at execution time
> and right before the segmentation fault);
>
> Please, can you confirm? Do you know why is it that doing so??
> Is there a way to prevent such behaviour?

You never check the return value of malloc, it's not guaranteed to give
you back the amount you requested. You also don't seem to be freeing the
memory you allocate.

This is very bad:
> // the following code is called about 2500 times.
> printf("allocating mem\n");
> my = (char*) malloc(256);
> printf("GOOD!\n");

You should do something like:

if ((my = (char *)malloc(256)) == NULL) {
    /* do some error handling */

}

...

/* finished using my, free memory */
free(my);


William

--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/


[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux