help C, pointer

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

Hello!
I'm doing homework for university in C
I have actually finished it, but i have some questions.....

[already having problems expressing myself]
[i will generalize]

Code:
#include <stdlib.h>

void *create(void);

int main()
{
  unsigned char *ptr; /* my pinter, that will point to arry of text (unsigned char */
  ptr=create(); /* allocate memory */
}

void *create(void)
{
  unsigned char *new_ptr;
  new_ptr=malloc(1000);
...
  return new_ptr;
}
Is that correct (well it works)?

now i want to do the same, but this time i don't want create to return anything, i want it to work directly with pointer (if what i say makes sense)

can someone, plz, show me example how to do that?

EDIT:
I've just read another article....
Ok, i want to make it clear
I want a variable (or pointer)
then with create allocate memory and assign it to variable (pointer?)
i will later use that variable (pointer?) for other stuff to refer to allocated memory
 

Djn

Well-Known Member

Reaction score: 67
Messages: 392

In order to do that, you would need to send the address of your pointer to the function.
Something like this (untested):
Code:
void main () {
  unsigned char *ptr;
  create(&ptr);
}

void create(unsigned char **ptr) {
  *ptr = malloc(1000);
}
Essentially, the function needs to know where to write the new address - and that's "the place in memory where the pointer is stored". If you read "&ptr" as "the address of ptr", and "unsigned char **ptr" as "a pointer to a pointer to an unsigned char", it's quite sensible. :)
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

It seems to work....

Code:
#include <stdlib.h>
#include <stdio.h>

void create(unsigned char **ptr);

int main () {
  unsigned char *ptr;
  if (ptr==NULL) printf ("err\n");
    create(&ptr);
  if (ptr==NULL) printf ("err\n");
}

void create(unsigned char **ptr) {
  *ptr = malloc(1000);
}
i see 1 err, so i think it's good [now i will try to implement it and see if it really works]

p.s. ptr==NULL stuff works under pcc, however not under gcc.

btw maybe there is other way to do this?
because it was my idea that i need to define pointer in main... maybe i don't?
 

Djn

Well-Known Member

Reaction score: 67
Messages: 392

Ah, good. I'm still slightly wary when doing any form of pointer handling. :)

BTW, since you asked for English corrections in that other thread: A "seam" is the line where two things are joined together; you want "seem".
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

here's my censored (simplified) function
it creates pascal like text string
**str is pointer to pointer
*txt is actual text to be inserted in pascal like string

Code:
void create(unsigned char [red]*[/red]*str, unsigned char *txt)
{
    unsigned int txt_len, tmp, i;

        tmp = txt_len = strlen(txt);
        [red]*[/red][color="Blue"]str = malloc(txt_max_len + txt_len_bytes);[/color]

// calculate and write down line lenght
        for (i=0; i<txt_len_bytes; i++) {
          [red]*[/red]str[i]=tmp % 256;
          tmp /= 256;
        }

// copy text
        for (i=txt_len_bytes; i<txt_len+txt_len_bytes; i++)
            [red]*[/red]str[i]=txt[i-txt_len_bytes];

// initialize rest of memory [not 100% necessary]
        while (i<txt_max_len+txt_len_bytes)
            [red]*[/red]str[i++]=0;
}
can you tell me what may cause segfault?
it was working when I used create to return pointer

i marked modified code red
blue makes segfault.... why?

txt_max_len and txt_len_bytes are predefined constants
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

What exactly is it you're trying to do?

Seems to me that you're basically just trying to duplicate a string, which can be done in much simpler ways than this.

Alphons
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

fonz said:
What exactly is it you're trying to do?

Seems to me that you're basically just trying to duplicate a string, which can be done in much simpler ways than this.

Alphons
That is exactly that i need to do, but not in easier manner.
I need to dynamically allocate space for string (i choose to emulate pascal like stings, because it's little harder, than just using c stings) assign string vaues... and then program functions for it (find, cut.... etc)

It's homework in data structures....
i need to use pointers
 

Djn

Well-Known Member

Reaction score: 67
Messages: 392

How do you call the create() function? It looks like the problem is the contents of **ptr.

Fonz: A pascal string is unterminated, but contains the string length before the first character. He's trying to create one of those from a C string.
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

Code:
unsigned char *ptr;
create(&ptr, "text");
if you want/need, i can show code that actually works (create which returns pointer)
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

killasmurf86 said:
can you tell me what may cause segfault?
it was working when I used create to return pointer

i marked modified code red
blue makes segfault.... why?

txt_max_len and txt_len_bytes are predefined constants
Are you sure it's the blue line that's causing the segfault?
I ran the following simplification and it works just fine:
Code:
#include <stdlib.h>

void
foo(unsigned char **ptr)
{
  *ptr=(unsigned char*)malloc(123*sizeof(unsigned char));
}

int main(int argc,char **argv)
{
  unsigned char *pointer;
  
  foo(&pointer);
  return 0;
}
Just a hunch, but I think it's the red stuff. Have you tried (*str) instead of *str? Remember that [] takes precedence over unary *.

Hope this helps,

Alphons
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

fonz said:
Are you sure it's the blue line that's causing the segfault?
I ran the following simplification and it works just fine:
Code:
#include <stdlib.h>

void
foo(unsigned char **ptr)
{
  *ptr=(unsigned char*)malloc(123*sizeof(unsigned char));
}

int main(int argc,char **argv)
{
  unsigned char *pointer;
  
  foo(&pointer);
  return 0;
}
Just a hunch, but I think it's the red stuff. Have you tried (*str) instead of *str? Remember that [] takes precedence over unary *.

Hope this helps,

Alphons


yes, I commented out everything else, I'll check your code
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

killasmurf86 said:
yes, I commented out everything else, I'll check your code
That's odd. From my experience, malloc() itself is highly unlikely to cause segfaults. The culprit is usually something you do afterwards.

Let me know what happens when you try my code.

Alphons
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

ok, that worked, now it break on second step...
i need to write to the allocated space.... from same function...
when i try, i get segfault
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

That's probably the (*str) vs. *str thing I mentioned earlier. Tried that yet?

Alphons
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

fonz said:
That's probably the (*str) vs. *str thing I mentioned earlier. Tried that yet?

Alphons


doesn't seem to work (tried many different flavors. lol)

EDIT:
It does work on gcc,
on pcc it also works, but somewhere error is generated, and when main ends ... it's being showed

I prefer pcc for this, because it supports comparing ptr==NULL, unlike gcc
pcc sets newly defined pointer to NULL

EDIT:
pcc generates err, but doesn't exit

EDIT:
i can hide it by adding return 0 in main;
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

Can you post the exact code you have now? Then I can try to compile and run it on my system to see what it does.

Alphons

Edit: I don't know much about pcc, so I can't help you with that.
 
OP
OP
graudeejs

graudeejs

Son of Beastie

Reaction score: 692
Messages: 4,615

remove:
return 0;
and compile with pcc, and then run it
otherwise it's fine
 

mjguzik

Member

Reaction score: 7
Messages: 36

If you don't return (insert some value here) in main, some random value is used and that's why 'an error is generated'. (Not only with pcc, with gcc too.) Your '(*str) == NULL' expression doesn't work as expected because afair the standard does not require local variables to be initialized. (Read as: *str is equal to some random value.) Initialize it explicitly to NULL and it will work.

Compile this code with -Wall to see scary things. ;)
 

Djn

Well-Known Member

Reaction score: 67
Messages: 392

I like using -Wall -ansi (and possibly -pedantic) when I'm not entirely sure if what I'm doing is a good idea. Warnings are good for you. (Note that -ansi doesn't allow // as a comment delimiter, at least not unless you compile as C99.)

Oh, and I quite like the TenDRA compiler (tcc); it's got very good warning/error messages.
 

fonz

Son of Beastie

Reaction score: 369
Messages: 2,560

mjguzik said:
afair the standard does not require local variables to be initialized. (Read as: *str is equal to some random value.)
That is correct.

Global (also called external in K&R terminology) variables are initialized to zero by default (i.e. when not explicitly initialized), as are static variables. And it's ok to depend on that. It may be considered bad style, but it is technically correct. Local (also called automatic in K&R terminology) variables on the other hand have undefined values when not explicitly initialized. If I'm not mistaken, compilers are free to initialize those to zero too, but that should really not be depended upon if you desire any degree of portability.

Of course, the easiest way to avoid problems is to just always explicitly initialize your variables ;)

mjguzik said:
Compile this code with -Wall to see scary things. ;)
Not scary, educational :p

Enabling warnings is often a good idea because it may point out dubious constructions and/or things that, although syntactically correct, just don't mean what's intended. Occasionally running Lint will also help you writing clean code :stud

Alphons
 

hydra

Well-Known Member

Reaction score: 27
Messages: 272

I always compile my code with -Wall, it's really helpful sometimes. Static or automatic variables, always initialize the value !

OK:
Code:
int p;

p = f();
if(p == 0)
NOT OK:
Code:
int p;

if(p == 0)
If you run i386, be sure to check out devel/valgrind, it helps a lot !
 
Top