Jump to content

why is that different? [solved]

- - - - -

  • Please log in to reply
3 replies to this topic

#1
qpai

qpai

    Newbie

  • Members
  • Pip
  • 2 posts
Hi,

I have some problems with the code below. (I truncated it, because its much easier to understand this way)
The problem is that the program exits with Seg. Fault., and I cannot figure out why.

#include <math.h>

#include <stdlib.h>

#include <string.h>


void novel(char *** names, int meret){

    int i = 0;

    if(meret == 0){ 

        *names=(char**)malloc(sizeof(char*)*10); 

        while(i<10){  

            *names[i] = (char*)malloc(sizeof(char)*50);

            i++;

        }       

    }   

    return;

}


void olvas(){

    char** names;

    int meret = 0;

    novel(&names, meret);   

}   

  

int main(){

    olvas();

}

However, if I don't pass the "char** names" to the other function, rather than allocating it within the "olvas" function, everything works fine.:

void olvas(){

    int i = 0;

    char** names;

    names=(char**)malloc(sizeof(char*)*10);


    while(i<10){

        names[i] = (char*)malloc(sizeof(char)*50);

        i++;

    }

    //int meret = 0;

    //novel(&names, meret);

}   

 

int main(){

    olvas();

}


I use gcc, but I dont really know what is the proper way to find the cause of the problem with gdb.
I can find which line causes the problem:
Program received signal SIGSEGV, Segmentation fault.

0x08048a46 in novel (names=0xbffff57c, meret=0) at fgvek.c:25

25

and I can check the value of the variables, but I cannot figure it out.
(One more question what is not related to this topic : Should I keep using gcc+gdb, or should I look for an IDE)

Thanks in advance,
qpai

#2
zoranh

zoranh

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts
In this line:
*names[i] = (char*)malloc(sizeof(char)*50);
Operator [] has higher precedence than dereference operator *. You should change the line into this:
(*names)[i] = (char*)malloc(sizeof(char)*50);


#3
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
or just simply names[i] = malloc(50); Note that sizeof(char) is guarenteed to always be 1 so there is no point multiplying 50 by 1. Also in C language the return value of malloc need not be typecast. That is not true in c++, but in c++ you would not want to use malloc() anyway.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4
qpai

qpai

    Newbie

  • Members
  • Pip
  • 2 posts
Thank you both!

(Do I need to mark this thread solved, or anything like that? (I'm a newbie))




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users