开发者

returning pointer to a character array from a function in a different file other than main

I can't return a pointer to a character array from a different file other than the main function. It always says "segmentation fault". But if I write the function in the same file as main, There is no problem.

/* this is in mainfunc.c file*/
int main()
{


    char ch[5]={'a','b','c','d','\0'};
    char *res=retchararray(ch);
    printf("%s\n",res);/*I get segmentation fault only when I use this printf*/

}

开发者_JAVA技巧/* this function is in other file newfile.c */

char *retchararray( char *p){

    char *str;
    str=p;
    unsigned int len=strlen(p);

    *(str+len)='e';
    *(str+len+1)='\0';

    return str;

}

I use netbeans on Mac OS to do C Programming.

Can some please tell me what is the problem? Or Am I doing some mistake here?


The function retchararray overflows your array. You use more memory than you have reserved. This happens in *(str+len+1) = '\0' and causes the segfault.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜