Matt Dunbar
Matt Dunbar

Reputation: 950

Seg Fault (Whats Wrong, strcpy)

In GDB I get:

 
(gdb) backtrace
0  0xb7d91544 in strcpy () from /lib/libc.so.6
1  0x08048982 in ISBN::ISBN(char const*, ISBNPrefix&) ()
2  0x08048d4a in main ()
(gdb)

From this code:

ISBN::ISBN(const char* str, ISBNPrefix& list) {
    if(isValid(str)) {
            isSet = true;
            sprintf(*isbnStr,"%s",str);
    }
}

What exactly would be causing this?

isbnStr is created in the header:

class ISBN
{
 ...
    char* isbnStr[11];
 ...

Any ideas on what I could be doing here to cause this seg fault?

The call in main is:

ISBN* isbn = new ISBN("7999999008",*prefix);

Upvotes: 0

Views: 289

Answers (3)

Sion Sheevok
Sion Sheevok

Reputation: 4217

You are trying to copy the string at str (a char*) into isbnStr[0] (a char*), but while isbnStr is a valid a array of 11 char*, those char*s are uninitialized and pointing to garbage addresses. Allocate memory for isbnStr[0] through isbnStr[10].

Note: I'm assuming you do mean to have isbnStr being an array of 11 char*s, for whatever reason. If you want isbnStr to be an array of 11 characters, declare it as char isbnStr[11] and don't dereference isbnStr in your sprintf.

Upvotes: 0

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

Are you doing anything to initialize isbnStr? If not, it is probably an invalid pointer and that can cause your program to crash.

Upvotes: 0

Yuliy
Yuliy

Reputation: 17718

isbnStr is an array of strings (or more specifically character pointers), not an array of characters. I think you meant to do char isbnStr[11];

Upvotes: 8

Related Questions