0

I'm having problems with array of struct. I'm trying to copy a part of a string to an element of an array of struct. (sorry if it does not sound so clear)

here is my code

#include <stdio.h>
#include <string.h>

struct dict {

char key[1024];

char value[16384];

int level;

};

int main()
{
struct dict entry[2562];
char str[]="i will finish my mp";
int j=0;
int i = 0;
char temp[1024];
char a =0;

while(a != 'h' ){
    a = str[i];
    temp[i] = str[i];
    i++;
} 
strcpy(entry[0].value,str);
puts(entry[0].value);



return 0;
}

It compiles but it does segmentation fault and I don't know what's wrong with it please help

6
  • 1
    struct dict entry[2562]; is possibly a bit too big to fit in automatic storage ("on the stack") Make it global, or allocate dynamically. Commented Mar 7, 2012 at 12:12
  • You may be getting segfault because you allocate large array struct dict entry[2562] on the stack. Try moving it out of the function and see if it works. Commented Mar 7, 2012 at 12:13
  • Try running it in a debugger, it will help you pinpoint the error location and let you examine variables to see what might be the problem. Commented Mar 7, 2012 at 12:16
  • @triclosan I'm trying to copy the str until finish Commented Mar 7, 2012 at 12:26
  • @dasblinkenlight I still get segfault even if I made it global Commented Mar 7, 2012 at 12:27

2 Answers 2

3

while(a != 't' ) this is infinite loop

did you mean

char a = 0xff;
while(a != '\0'){...} 

?

ADD

for this task for is more clear

int cnt = srtlen(str);
for(int i = 0; i < cnt; i++)
    temp[i] = str[i];
Sign up to request clarification or add additional context in comments.

2 Comments

I mean while(a != 'h') I'm trying to copy the string until finish.
jellygurl, How is 'h' related to finish of a string?...as @triclosan pointed out it should be '\0'
3

One possibility of segmentation fault in your code is stack overflow.

Each variable of your structure will be of about 17KB size and you are creating 2562 such variables which means a total of about 43554KB needs to be allocated which 42MB.

You can check the limit of your max stack size by doing ulimit -s from the shell, if it is less than 43554 you hit stackoverflow.

If this is the case you might try increasing the stack limit by doing ulimit -s 43554 or a bit more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.