LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C - Malloc causing segfault (https://www.linuxquestions.org/questions/programming-9/c-malloc-causing-segfault-796755/)

golmschenk 03-20-2010 05:47 PM

C - Malloc causing segfault
 
Code:

#include <stdio.h>
#include <stdlib.h>
#include "mm_public.h"
int main (){
struct timeval time_start, time_end;
int j;
void **Mem_Stuff;
int i;
        /* start timer */
fprintf (stderr, "Good Thus Far 1\n");
j = gettimeofday (&time_start, (void *)NULL);
fprintf (stderr, "Good Thus Far 2\n");
for (i=0;i<10000;i++){
        fprintf (stderr, "Good Thus Far 3\n");
        Mem_Stuff[i] = malloc(64);
        fprintf (stderr, "Good Thus Far 4\n");
}
for (i=0;i<10000;i++){
        free (Mem_Stuff[i]);
}
j = gettimeofday (&time_end, (void *)NULL);
fprintf (stderr, "Time taken =  %f msec\n",comp_time (time_start, time_end)/1000.0);
return 0;
}

Output gets to "Good Thus Far 3" then segfaults. Not sure why. Any suggestions? Thanks!

Sergei Steshenko 03-20-2010 05:53 PM

Quote:

Originally Posted by golmschenk (Post 3905966)
Code:

#include <stdio.h>
#include <stdlib.h>
#include "mm_public.h"
int main (){
struct timeval time_start, time_end;
int j;
void **Mem_Stuff;
int i;
        /* start timer */
fprintf (stderr, "Good Thus Far 1\n");
j = gettimeofday (&time_start, (void *)NULL);
fprintf (stderr, "Good Thus Far 2\n");
for (i=0;i<10000;i++){
        fprintf (stderr, "Good Thus Far 3\n");
        Mem_Stuff[i] = malloc(64);
        fprintf (stderr, "Good Thus Far 4\n");
}
for (i=0;i<10000;i++){
        free (Mem_Stuff[i]);
}
j = gettimeofday (&time_end, (void *)NULL);
fprintf (stderr, "Time taken =  %f msec\n",comp_time (time_start, time_end)/1000.0);
return 0;
}

Output gets to "Good Thus Far 3" then segfaults. Not sure why. Any suggestions? Thanks!

And why do you think it's 'malloc' which causes segmentation fault and not the assignment ?

Modify your code to become, say

Code:

fprintf (stderr, "Good Thus Far 3\n");
void *tmp = malloc(64);
fprintf (stderr, "Good Thus Far 4\n");
Mem_Stuff[i] = tmp;
fprintf (stderr, "Good Thus Far 5\n");

and recheck.

neonsignal 03-20-2010 05:56 PM

The Mem_Stuff that you have declared is a 'pointer to a pointer to something'. You are treating it as a 'array of pointers', which is also fine. However, you have not made space for the array, so when you attempt to assign to one of the pointers, you get the fault.

You need to first allocate space for the array itself, before allocating the spaces that the pointer elements are going to point to.

=== edit - see above post! ===

golmschenk 03-21-2010 03:21 PM

Great, that helps a bunch. Thanks!


All times are GMT -5. The time now is 03:53 AM.